collections-generic-4.01/0000755000175000017500000000000011664401371015577 5ustar giovannigiovannicollections-generic-4.01/LICENSE.txt0000644000175000017500000002613610464140752017432 0ustar giovannigiovanni 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 APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. collections-generic-4.01/data/0000755000175000017500000000000010464140753016511 5ustar giovannigiovannicollections-generic-4.01/data/test/0000755000175000017500000000000011664401370017466 5ustar giovannigiovannicollections-generic-4.01/data/test/UnmodifiableBuffer.emptyCollection.version3.1.obj0000644000175000017500000000023710464140754030776 0ustar giovannigiovannisr8org.apache.commons.collections.buffer.UnmodifiableBufferoi?Mxpsr9org.apache.commons.collections.buffer.UnboundedFifoBufferϪ fUxpwxxcollections-generic-4.01/data/test/PredicatedCollection.emptyCollection.version3.1.obj0000644000175000017500000000055110464140762031324 0ustar giovannigiovannisr>org.apache.commons.collections.collection.PredicatedCollectionpvL predicatet*Lorg/apache/commons/collections/Predicate;xrQorg.apache.commons.collections.collection.AbstractSerializableCollectionDecoratorV4xpsrjava.util.ArrayListxaIsizexpw xxsr5org.apache.commons.collections.functors.TruePredicate.ՔQ&,xpcollections-generic-4.01/data/test/TreeBag.fullCollection.version3.obj0000644000175000017500000000014510464140762026221 0ustar giovannigiovannisr*org.apache.commons.collections.bag.TreeBagylxppwtAwtBwtCwxcollections-generic-4.01/data/test/TransformedSortedBag.fullCollection.version3.1.obj0000644000175000017500000000104010464140761031120 0ustar giovannigiovannisr7org.apache.commons.collections.bag.TransformedSortedBagXݶxr1org.apache.commons.collections.bag.TransformedBagK;8xxr?org.apache.commons.collections.collection.TransformedCollectionx@sL transformert,Lorg/apache/commons/collections/Transformer;xrQorg.apache.commons.collections.collection.AbstractSerializableCollectionDecoratorV4xpsr*org.apache.commons.collections.bag.TreeBagylxppwtAwtBwtCwxxsr6org.apache.commons.collections.functors.NOPTransformer=?wxpcollections-generic-4.01/data/test/TreeBag.emptyCollection.version3.obj0000644000175000017500000000010710464140763026414 0ustar giovannigiovannisr*org.apache.commons.collections.bag.TreeBagylxppwxcollections-generic-4.01/data/test/SequencedHashMap.fullCollection.version2.obj0000644000175000017500000000050610464140762030066 0ustar giovannigiovannisr/org.apache.commons.collections.SequencedHashMap.""& xpwtblahtblahvtfootfoovtbartbarvtbaztbazvttmpttmpvtgoshtgoshvtgollytgollyvtgeetgeevthellothellovtgoodbyetgoodbyevtwe'lltwe'llvtseetseevtyoutyouvtalltallvtagaintagainvtkeyptkey2tvaluepq~"xcollections-generic-4.01/data/test/PredicatedSortedBag.fullCollection.version3.1.obj0000644000175000017500000000103010464140764030702 0ustar giovannigiovannisr6org.apache.commons.collections.bag.PredicatedSortedBag/o +xr0org.apache.commons.collections.bag.PredicatedBag@gxr>org.apache.commons.collections.collection.PredicatedCollectionpvL predicatet*Lorg/apache/commons/collections/Predicate;xrQorg.apache.commons.collections.collection.AbstractSerializableCollectionDecoratorV4xpsr*org.apache.commons.collections.bag.TreeBagylxppwtAwtBwtCwxxsr5org.apache.commons.collections.functors.TruePredicate.ՔQ&,xpcollections-generic-4.01/data/test/LRUMap.fullCollection.version2.obj0000644000175000017500000000057610464140760026015 0ustar giovannigiovannisr%org.apache.commons.collections.LRUMap~̍C xr/org.apache.commons.collections.SequencedHashMap.""& xpwdtblahtblahvtfootfoovtbartbarvtbaztbazvttmpttmpvtgoshtgoshvtgollytgollyvtgeetgeevthellothellovtgoodbyetgoodbyevtwe'lltwe'llvtseetseevtyoutyouvtalltallvtagaintagainvtkeyptkey2tvaluepq~#xcollections-generic-4.01/data/test/SynchronizedSortedSet.emptyCollection.version3.1.obj0000644000175000017500000000041510464140765031562 0ustar giovannigiovannisr8org.apache.commons.collections.set.SynchronizedSortedSet&Cuxr@org.apache.commons.collections.collection.SynchronizedCollection!|rI "L collectiontLjava/util/Collection;LlocktLjava/lang/Object;xpsrjava.util.TreeSetݘP[xppwxq~collections-generic-4.01/data/test/PredicatedSet.emptyCollection.version3.1.obj0000644000175000017500000000064310464140762027766 0ustar giovannigiovannisr0org.apache.commons.collections.set.PredicatedSetYxr>org.apache.commons.collections.collection.PredicatedCollectionpvL predicatet*Lorg/apache/commons/collections/Predicate;xrQorg.apache.commons.collections.collection.AbstractSerializableCollectionDecoratorV4xpsrjava.util.HashSetD4xpw ?@xxsr5org.apache.commons.collections.functors.TruePredicate.ՔQ&,xpcollections-generic-4.01/data/test/PredicatedMap.fullCollection.version3.1.obj0000644000175000017500000000105410464140765027554 0ustar giovannigiovannisr0org.apache.commons.collections.map.PredicatedMapfٟ%L keyPredicatet*Lorg/apache/commons/collections/Predicate;LvaluePredicateq~xpsr5org.apache.commons.collections.functors.TruePredicate.ՔQ&,xpq~srjava.util.HashMap`F loadFactorI thresholdxp?@w tfootfoovtwe'lltwe'llvtseetseevptvaluetbaztbazvthellothellovtbartbarvtagaintagainvtkey2q~ tgoodbyetgoodbyevtyoutyouvtkeyptblahtblahvtgeetgeevttmpttmpvtgollytgollyvtgoshtgoshvtalltallvxxcollections-generic-4.01/data/test/PredicatedBuffer.emptyCollection.version3.1.obj0000644000175000017500000000074610464140760030446 0ustar giovannigiovannisr6org.apache.commons.collections.buffer.PredicatedBuffer F(rxr>org.apache.commons.collections.collection.PredicatedCollectionpvL predicatet*Lorg/apache/commons/collections/Predicate;xrQorg.apache.commons.collections.collection.AbstractSerializableCollectionDecoratorV4xpsr)org.apache.commons.collections.ArrayStack/Gxrjava.util.ArrayListxaIsizexpw xxsr5org.apache.commons.collections.functors.TruePredicate.ՔQ&,xpcollections-generic-4.01/data/test/UnmodifiableMap.emptyCollection.version3.1.obj0000644000175000017500000000022610464140755030301 0ustar giovannigiovannisr2org.apache.commons.collections.map.UnmodifiableMap%NDJxpsrjava.util.HashMap`F loadFactorI thresholdxp?@wxxcollections-generic-4.01/data/test/FixedSizeList.emptyCollection.version3.1.obj0000644000175000017500000000032110464140757027771 0ustar giovannigiovannisr1org.apache.commons.collections.list.FixedSizeList8 ;axrEorg.apache.commons.collections.list.AbstractSerializableListDecorator%B){kxpsrjava.util.ArrayListxaIsizexpw xxcollections-generic-4.01/data/test/UnmodifiableList.emptyCollection.version3.1.obj0000644000175000017500000000032410464140761030473 0ustar giovannigiovannisr4org.apache.commons.collections.list.UnmodifiableList[<}xrEorg.apache.commons.collections.list.AbstractSerializableListDecorator%B){kxpsrjava.util.ArrayListxaIsizexpw xxcollections-generic-4.01/data/test/MultiHashMap.emptyCollection.version2.obj0000644000175000017500000000026710464140757027450 0ustar giovannigiovannisr+org.apache.commons.collections.MultiHashMap LmNametLjava/lang/String;xrjava.util.HashMap`F loadFactorI thresholdxp?@w xt MultiMap-26collections-generic-4.01/data/test/SynchronizedCollection.fullCollection.version3.1.obj0000644000175000017500000000115110464140754031541 0ustar giovannigiovannisr@org.apache.commons.collections.collection.SynchronizedCollection!|rI "L collectiontLjava/util/Collection;LlocktLjava/lang/Object;xpsrjava.util.ArrayListxaIsizexpwttOnesrjava.lang.Integer⠤8Ivaluexrjava.lang.Number xptThreepsq~tOnesrjava.lang.DoubleJ)kDvaluexq~ @srjava.lang.Floatɢ<Fvaluexq~ @tSeventEighttNinesq~ srjava.lang.ShorthM74`RSvaluexq~ srjava.lang.Long;̏#Jvaluexq~ tThirteent14t15srjava.lang.ByteN`PBvaluexq~ xq~collections-generic-4.01/data/test/FastTreeMap.fullCollection.version1.obj0000644000175000017500000000116610464140756027070 0ustar giovannigiovannisr*org.apache.commons.collections.FastTreeMapx9s]'ZfastLmaptLjava/util/TreeMap;xrjava.util.TreeMap >-%jL comparatortLjava/util/Comparator;xppwtagaintagainvtalltallvtbartbarvtbaztbazvtblahtblahvtfootfoovtgeetgeevtgollytgollyvtgoodbyetgoodbyevtgoshtgoshvthellothellovtkeyptkey2tvaluet nonnullkeyq~tseetseevttmpttmpvtwe'lltwe'llvtyoutyouvxsq~pwq~q~q~q~q~ q~ q~ q~ q~ q~q~q~q~q~q~q~q~q~q~q~q~q~q~pq~q~q~q~q~q~ q~!q~"q~#q~$q~%q~&xcollections-generic-4.01/data/test/SynchronizedBuffer.fullCollection.version3.1.obj0000644000175000017500000000131210464140756030660 0ustar giovannigiovannisr8org.apache.commons.collections.buffer.SynchronizedBuffer̜bݘksxr@org.apache.commons.collections.collection.SynchronizedCollection!|rI "L collectiontLjava/util/Collection;LlocktLjava/lang/Object;xpsr9org.apache.commons.collections.buffer.UnboundedFifoBufferϪ fUxpwttOnesrjava.lang.Integer⠤8Ivaluexrjava.lang.Number xptThreesq~ tOnesrjava.lang.DoubleJ)kDvaluexq~ @srjava.lang.Floatɢ<Fvaluexq~ @tSeventEighttNinesq~ srjava.lang.ShorthM74`RSvaluexq~ srjava.lang.Long;̏#Jvaluexq~ tThirteent14t15srjava.lang.ByteN`PBvaluexq~ xq~collections-generic-4.01/data/test/PredicatedBuffer.fullCollection.version3.1.obj0000644000175000017500000000060510464140764030250 0ustar giovannigiovannisr>org.apache.commons.collections.collection.PredicatedCollectionpvL predicatet*Lorg/apache/commons/collections/Predicate;xrQorg.apache.commons.collections.collection.AbstractSerializableCollectionDecoratorV4xpsrjava.util.ArrayListxaIsizexpw t1t3t5t7t2t4t6xxsr5org.apache.commons.collections.functors.TruePredicate.ՔQ&,xpcollections-generic-4.01/data/test/NullComparator.version2.obj20000644000175000017500000000033310464140756024760 0ustar giovannigiovannisr9org.apache.commons.collections.comparators.NullComparator8v.Y-Z nullsAreHighLnonNullComparatortLjava/util/Comparator;xpsr?org.apache.commons.collections.comparators.ComparableComparator%n7xpcollections-generic-4.01/data/test/DualHashBidiMap.fullCollection.version3.obj0000644000175000017500000000063110464140755027631 0ustar giovannigiovannisr6org.apache.commons.collections.bidimap.DualHashBidiMap[Pxpsrjava.util.HashMap`F loadFactorI thresholdxp?@w tfootfoovtwe'lltwe'llvtseetseevtbaztbazvthellothellovtbartbarvtagaintagainvtkey2tvalueptvalue2tgoodbyetgoodbyevtyoutyouvtkeyptblahtblahvtgeetgeevttmpttmpvtgollytgollyvtgoshtgoshvtalltallvxxcollections-generic-4.01/data/test/DualTreeBidiMap.emptyCollection.version3.Test2.obj0000644000175000017500000000054110464140756031042 0ustar giovannigiovannisr6org.apache.commons.collections.bidimap.DualTreeBidiMap[QL comparatortLjava/util/Comparator;xpsr-%jL comparatorq~xpq~wxxcollections-generic-4.01/data/test/PredicatedCollection.fullCollection.version3.1.obj0000644000175000017500000000060510464140765031133 0ustar giovannigiovannisr>org.apache.commons.collections.collection.PredicatedCollectionpvL predicatet*Lorg/apache/commons/collections/Predicate;xrQorg.apache.commons.collections.collection.AbstractSerializableCollectionDecoratorV4xpsrjava.util.ArrayListxaIsizexpw t1t3t5t7t2t4t6xxsr5org.apache.commons.collections.functors.TruePredicate.ՔQ&,xpcollections-generic-4.01/data/test/CircularFifoBuffer.fullCollection.version3.1.obj0000644000175000017500000000110210464140755030545 0ustar giovannigiovannisr8org.apache.commons.collections.buffer.CircularFifoBufferEZxr7org.apache.commons.collections.buffer.BoundedFifoBufferMl4Y I maxElementsxpdwttOnesrjava.lang.Integer⠤8Ivaluexrjava.lang.Number xptThreesq~tOnesrjava.lang.DoubleJ)kDvaluexq~@srjava.lang.Floatɢ<Fvaluexq~@tSeventEighttNinesq~ srjava.lang.ShorthM74`RSvaluexq~ srjava.lang.Long;̏#Jvaluexq~ tThirteent14t15srjava.lang.ByteN`PBvaluexq~xcollections-generic-4.01/data/test/MapBackedSet.emptyCollection.version3.1.obj0000644000175000017500000000031310464140763027524 0ustar giovannigiovannisr/org.apache.commons.collections.set.MapBackedSet]P"oL dummyValuetLjava/lang/Object;LmaptLjava/util/Map;xppsr,org.apache.commons.collections.map.HashedMap/ FOsxpw ?@xcollections-generic-4.01/data/test/CaseInsensitiveMap.fullCollection.version3.obj0000644000175000017500000000052410464140760030441 0ustar giovannigiovannisr5org.apache.commons.collections.map.CaseInsensitiveMap!nxpw ?@ tfootfoovtwe'lltwe'llvtseetseevtbaztbazvthellothellovtbartbarvtagaintagainvtkey2tvaluepq~tgoodbyetgoodbyevtkeyptyoutyouvtblahtblahvtgeetgeevttmpttmpvtgollytgollyvtgoshtgoshvtalltallvxcollections-generic-4.01/data/test/UnmodifiableMap.fullCollection.version3.1.obj0000644000175000017500000000062110464140762030102 0ustar giovannigiovannisr2org.apache.commons.collections.map.UnmodifiableMap%NDJxpsrjava.util.HashMap`F loadFactorI thresholdxp?@w tfootfoovtwe'lltwe'llvtseetseevptvaluetbaztbazvthellothellovtbartbarvtagaintagainvtkey2q~ tgoodbyetgoodbyevtyoutyouvtkeyptblahtblahvtgeetgeevttmpttmpvtgollytgollyvtgoshtgoshvtalltallvxxcollections-generic-4.01/data/test/FixedSizeMap.emptyCollection.version3.1.obj0000644000175000017500000000022310464140756027573 0ustar giovannigiovannisr/org.apache.commons.collections.map.FixedSizeMapggѯtxpsrjava.util.HashMap`F loadFactorI thresholdxp?@wxxcollections-generic-4.01/data/test/FastArrayList.emptyCollection.version1.obj0000644000175000017500000000025510464140764027636 0ustar giovannigiovannisr,org.apache.commons.collections.FastArrayList axZfastLlisttLjava/util/ArrayList;xrjava.util.ArrayListxaIsizexpw xsq~w xcollections-generic-4.01/data/test/TransformedList.emptyCollection.version3.1.obj0000644000175000017500000000066110464140756030371 0ustar giovannigiovannisr3org.apache.commons.collections.list.TransformedList[aUxr?org.apache.commons.collections.collection.TransformedCollectionx@sL transformert,Lorg/apache/commons/collections/Transformer;xrQorg.apache.commons.collections.collection.AbstractSerializableCollectionDecoratorV4xpsrjava.util.ArrayListxaIsizexpw xxsr6org.apache.commons.collections.functors.NOPTransformer=?wxpcollections-generic-4.01/data/test/TransformedMap.emptyCollection.version3.1.obj0000644000175000017500000000047110464140764030171 0ustar giovannigiovannisr1org.apache.commons.collections.map.TransformedMapaw?]ZpLkeyTransformert,Lorg/apache/commons/collections/Transformer;LvalueTransformerq~xpsr6org.apache.commons.collections.functors.NOPTransformer=?wxpq~srjava.util.HashMap`F loadFactorI thresholdxp?@wxxcollections-generic-4.01/data/test/FixedSizeMap.fullCollection.version3.1.obj0000644000175000017500000000061610464140765027405 0ustar giovannigiovannisr/org.apache.commons.collections.map.FixedSizeMapggѯtxpsrjava.util.HashMap`F loadFactorI thresholdxp?@w tfootfoovtwe'lltwe'llvtseetseevptvaluetbaztbazvthellothellovtbartbarvtagaintagainvtkey2q~ tgoodbyetgoodbyevtyoutyouvtkeyptblahtblahvtgeetgeevttmpttmpvtgollytgollyvtgoshtgoshvtalltallvxxcollections-generic-4.01/data/test/FastHashMap.emptyCollection.version1.obj0000644000175000017500000000031010464140764027235 0ustar giovannigiovannisr*org.apache.commons.collections.FastHashMapT&ZfastLmaptLjava/util/HashMap;xrjava.util.HashMap`F loadFactorI thresholdxp?@w xsq~?@w xcollections-generic-4.01/data/test/ComparatorChain.version2.obj0000644000175000017500000000065110464140764025010 0ustar giovannigiovannisr:org.apache.commons.collections.comparators.ComparatorChain3}ZisLockedLcomparatorChaintLjava/util/List;L orderingBitstLjava/util/BitSet;xpsrjava.util.ArrayListxaIsizexpw srOorg.apache.commons.collections.comparators.TestComparatorChain$ColumnComparatorJx8a{WIcolIndexxpsq~sq~xsrjava.util.BitSetn~94![bitst[Jxpur[Jx uxpcollections-generic-4.01/data/test/ListOrderedSet.fullCollection.version3.1.obj0000644000175000017500000000140510464140761027742 0ustar giovannigiovannisr1org.apache.commons.collections.set.ListOrderedSetӞSLsetOrdertLjava/util/List;xrCorg.apache.commons.collections.set.AbstractSerializableSetDecoratorkxpsrjava.util.HashSetD4xpw ?@srjava.lang.Integer⠤8Ivaluexrjava.lang.Number xptThreepsrjava.lang.ShorthM74`RSvaluexq~ srjava.lang.ByteN`PBvaluexq~tEightsrjava.lang.DoubleJ)kDvaluexq~@srjava.lang.Floatɢ<Fvaluexq~@t14srjava.lang.Long;̏#Jvaluexq~ sq~tSeventNinetThirteent15sq~ ttOnexxsrjava.util.ArrayListxaIsizexpwq~q~q~q~ pq~q~q~q~q~q~q~q~ q~q~q~q~q~ xcollections-generic-4.01/data/test/ReferenceMap.fullCollection.version3.1.obj0000644000175000017500000000055610464140765027414 0ustar giovannigiovannisr/org.apache.commons.collections.map.ReferenceMapIxpw?@ tfootfoovtwe'lltwe'llvt nonnullkeytvaluetseetseevtbaztbazvthellothellovtbartbarvtagaintagainvtkey2q~tgoodbyetgoodbyevtkeyt nonnullvaluetyoutyouvtblahtblahvtgeetgeevttmpttmpvtgollytgollyvtgoshtgoshvtalltallvpxcollections-generic-4.01/data/test/CursorableLinkedList.fullCollection.version1.obj0000644000175000017500000000030410464140756030772 0ustar giovannigiovannisr3org.apache.commons.collections.CursorableLinkedListz,zI _modCountL_cursorstLjava/util/List;xpsrjava.util.ArrayListxaIsizexpw xwt1t3t4q~xcollections-generic-4.01/data/test/IdentityMap.emptyCollection.version3.obj0000644000175000017500000000012210464140761027325 0ustar giovannigiovannisr.org.apache.commons.collections.map.IdentityMap&$xpw ?@xcollections-generic-4.01/data/test/HashBag.emptyCollection.version3.obj0000644000175000017500000000010610464140754026377 0ustar giovannigiovannisr*org.apache.commons.collections.bag.HashBag-%jL comparatortLjava/util/Comparator;xppwtagaintagainvtalltallvtbartbarvtbaztbazvtblahtblahvtfootfoovtgeetgeevtgollytgollyvtgoodbyetgoodbyevtgoshtgoshvthellothellovtkeyptkey2tvaluet nonnullkeyq~tseetseevttmpttmpvtwe'lltwe'llvtyoutyouvxxcollections-generic-4.01/data/test/PredicatedBag.emptyCollection.version3.1.obj0000644000175000017500000000066410464140755027731 0ustar giovannigiovannisr0org.apache.commons.collections.bag.PredicatedBag@gxr>org.apache.commons.collections.collection.PredicatedCollectionpvL predicatet*Lorg/apache/commons/collections/Predicate;xrQorg.apache.commons.collections.collection.AbstractSerializableCollectionDecoratorV4xpsr*org.apache.commons.collections.bag.HashBagorg.apache.commons.collections.collection.PredicatedCollectionpvL predicatet*Lorg/apache/commons/collections/Predicate;xrQorg.apache.commons.collections.collection.AbstractSerializableCollectionDecoratorV4xpsrjava.util.TreeSetݘP[xppwsrjava.lang.Integer⠤8Ivaluexrjava.lang.Number xpsq~sq~sq~sq~ sq~ sq~ sq~sq~sq~sq~sq~sq~sq~sq~sq~sq~!sq~#sq~%sq~'sq~)sq~+sq~-sq~/sq~1sq~3sq~5sq~7sq~9sq~;xxsr5org.apache.commons.collections.functors.TruePredicate.ՔQ&,xpcollections-generic-4.01/data/test/ListOrderedSet.emptyCollection.version3.1.obj0000644000175000017500000000043610464140757030146 0ustar giovannigiovannisr1org.apache.commons.collections.set.ListOrderedSetӞSLsetOrdertLjava/util/List;xrCorg.apache.commons.collections.set.AbstractSerializableSetDecoratorkxpsrjava.util.HashSetD4xpw ?@xxsrjava.util.ArrayListxaIsizexpwxcollections-generic-4.01/data/test/BoundedFifoBuffer.emptyCollection.version3.1.obj0000644000175000017500000000014510464140763030562 0ustar giovannigiovannisr7org.apache.commons.collections.buffer.BoundedFifoBufferMl4Y I maxElementsxpdwxcollections-generic-4.01/data/test/UnboundedFifoBuffer.emptyCollection.version3.1.obj0000644000175000017500000000012510464140755031124 0ustar giovannigiovannisr9org.apache.commons.collections.buffer.UnboundedFifoBufferϪ fUxpwxcollections-generic-4.01/data/test/TransformedCollection.emptyCollection.version3.1.obj0000644000175000017500000000055710464140762031552 0ustar giovannigiovannisr?org.apache.commons.collections.collection.TransformedCollectionx@sL transformert,Lorg/apache/commons/collections/Transformer;xrQorg.apache.commons.collections.collection.AbstractSerializableCollectionDecoratorV4xpsrjava.util.ArrayListxaIsizexpw xxsr6org.apache.commons.collections.functors.NOPTransformer=?wxpcollections-generic-4.01/data/test/Flat3Map.fullCollection.version3.1.obj0000644000175000017500000000050210464140761026452 0ustar giovannigiovannisr+org.apache.commons.collections.map.Flat3Map~qxpwtfootfoovtwe'lltwe'llvtseetseevtbaztbazvthellothellovtbartbarvtagaintagainvtkey2tvaluetgoodbyetgoodbyevtkeyptyoutyouvtblahtblahvtgeetgeevttmpttmpvtgollytgollyvtgoshtgoshvtalltallvpq~xcollections-generic-4.01/data/test/LazySortedMap.fullCollection.version3.1.obj0000644000175000017500000000137210464140760027606 0ustar giovannigiovannisr0org.apache.commons.collections.map.LazySortedMap%#D5xr*org.apache.commons.collections.map.LazyMapn唂yLfactoryt,Lorg/apache/commons/collections/Transformer;xpsr:org.apache.commons.collections.functors.FactoryTransformerb)]LiFactoryt(Lorg/apache/commons/collections/Factory;xpsr7org.apache.commons.collections.functors.ConstantFactory$ m[*L iConstanttLjava/lang/Object;xppsrjava.util.TreeMap >-%jL comparatortLjava/util/Comparator;xppwtagaintagainvtalltallvtbartbarvtbaztbazvtblahtblahvtfootfoovtgeetgeevtgollytgollyvtgoodbyetgoodbyevtgoshtgoshvthellothellovtkeyptkey2tvaluet nonnullkeyq~%tseetseevttmpttmpvtwe'lltwe'llvtyoutyouvxxcollections-generic-4.01/data/test/HashBag.fullCollection.version3.obj0000644000175000017500000000014410464140762026204 0ustar giovannigiovannisr*org.apache.commons.collections.bag.HashBag-%jL comparatortLjava/util/Comparator;xppwxxcollections-generic-4.01/data/test/UnmodifiableSortedSet.fullCollection.version3.1.obj0000644000175000017500000000074710464140760031310 0ustar giovannigiovannisr8org.apache.commons.collections.set.UnmodifiableSortedSetzLcxpsrjava.util.TreeSetݘP[xppwsrjava.lang.Integer⠤8Ivaluexrjava.lang.Number xpsq~sq~sq~sq~ sq~ sq~ sq~sq~sq~sq~sq~sq~sq~sq~sq~sq~!sq~#sq~%sq~'sq~)sq~+sq~-sq~/sq~1sq~3sq~5sq~7sq~9sq~;xxcollections-generic-4.01/data/test/UnmodifiableOrderedMap.fullCollection.version3.1.obj0000644000175000017500000000121010464140757031406 0ustar giovannigiovannisr9org.apache.commons.collections.map.UnmodifiableOrderedMappfM%xpsr1org.apache.commons.collections.map.ListOrderedMap%o53fL insertOrdertLjava/util/List;xpsrjava.util.ArrayListxaIsizexpwtagaintalltbartbaztblahtfootgeetgollytgoodbyetgoshthellotkeytkey2tseettmptwe'lltyoupxsrjava.util.HashMap`F loadFactorI thresholdxp?@w q~ tgoshvq~pq~tallvptvalueq~ tbazvq~twe'llvq~ tbarvq~tblahvq~tyouvq~thellovq~tseevq~q~q~ ttmpvq~ tgollyvq~tagainvq~tgeevq~tgoodbyevq~tfoovxxxcollections-generic-4.01/data/test/SingletonMap.fullCollection.version3.1.obj0000644000175000017500000000030310464140760027441 0ustar giovannigiovannisr/org.apache.commons.collections.map.SingletonMap <ʐACLkeytLjava/lang/Object;Lvalueq~xpsrjava.lang.Integer⠤8Ivaluexrjava.lang.Number xpsq~collections-generic-4.01/data/test/TransformedMap.fullCollection.version3.1.obj0000644000175000017500000000106410464140755027774 0ustar giovannigiovannisr1org.apache.commons.collections.map.TransformedMapaw?]ZpLkeyTransformert,Lorg/apache/commons/collections/Transformer;LvalueTransformerq~xpsr6org.apache.commons.collections.functors.NOPTransformer=?wxpq~srjava.util.HashMap`F loadFactorI thresholdxp?@w tfootfoovtwe'lltwe'llvtseetseevptvaluetbaztbazvthellothellovtbartbarvtagaintagainvtkey2q~ tgoodbyetgoodbyevtyoutyouvtkeyptblahtblahvtgeetgeevttmpttmpvtgollytgollyvtgoshtgoshvtalltallvxxcollections-generic-4.01/data/test/LRUMap.fullCollection.version3.obj0000644000175000017500000000051410464140763026011 0ustar giovannigiovannisr)org.apache.commons.collections.map.LRUMapTxpwd?@tagaintblahvtalltfoovtbartbarvtbaztbazvtblahttmpvtfootgoshvtgeetgollyvtgollytgeevtgoodbyethellovtgoshtgoodbyevthellotwe'llvtkeytseevtkey2tyouvtseetallvttmptagainvtwe'llptyoutvaluepq~"xcollections-generic-4.01/data/test/ReferenceIdentityMap.emptyCollection.version3.1.obj0000644000175000017500000000014110464140756031310 0ustar giovannigiovannisr7org.apache.commons.collections.map.ReferenceIdentityMapmxpw?@pxcollections-generic-4.01/data/test/BlockingBuffer.emptyCollection.version3.1.obj0000644000175000017500000000056710464140763030136 0ustar giovannigiovannisr4org.apache.commons.collections.buffer.BlockingBufferHxr8org.apache.commons.collections.buffer.SynchronizedBuffer̜bݘksxr@org.apache.commons.collections.collection.SynchronizedCollection!|rI "L collectiontLjava/util/Collection;LlocktLjava/lang/Object;xpsr9org.apache.commons.collections.buffer.UnboundedFifoBufferϪ fUxpwxq~collections-generic-4.01/data/test/TransformedBag.fullCollection.version3.1.obj0000644000175000017500000000073110464140763027747 0ustar giovannigiovannisr1org.apache.commons.collections.bag.TransformedBagK;8xxr?org.apache.commons.collections.collection.TransformedCollectionx@sL transformert,Lorg/apache/commons/collections/Transformer;xrQorg.apache.commons.collections.collection.AbstractSerializableCollectionDecoratorV4xpsr*org.apache.commons.collections.bag.HashBag-%jL comparatorq~xppwxxcollections-generic-4.01/data/test/BoundedFifoBuffer.fullCollection.version3.1.obj0000644000175000017500000000077310464140753030374 0ustar giovannigiovannisr7org.apache.commons.collections.buffer.BoundedFifoBufferMl4Y I maxElementsxpwttOnesrjava.lang.Integer⠤8Ivaluexrjava.lang.Number xptThreesq~tOnesrjava.lang.DoubleJ)kDvaluexq~@srjava.lang.Floatɢ<Fvaluexq~@tSeventEighttNinesq~ srjava.lang.ShorthM74`RSvaluexq~ srjava.lang.Long;̏#Jvaluexq~ tThirteent14t15srjava.lang.ByteN`PBvaluexq~xcollections-generic-4.01/data/test/TransformedSortedMap.fullCollection.version3.1.obj0000644000175000017500000000121010464140763031145 0ustar giovannigiovannisr7org.apache.commons.collections.map.TransformedSortedMapvx;xr1org.apache.commons.collections.map.TransformedMapaw?]ZpLkeyTransformert,Lorg/apache/commons/collections/Transformer;LvalueTransformerq~xpsr6org.apache.commons.collections.functors.NOPTransformer=?wxpq~srjava.util.TreeMap >-%jL comparatortLjava/util/Comparator;xppwtagaintagainvtalltallvtbartbarvtbaztbazvtblahtblahvtfootfoovtgeetgeevtgollytgollyvtgoodbyetgoodbyevtgoshtgoshvthellothellovtkeyptkey2tvaluet nonnullkeyq~!tseetseevttmpttmpvtwe'lltwe'llvtyoutyouvxxcollections-generic-4.01/data/test/ComparableComparator.version2.obj0000644000175000017500000000012410464140760026022 0ustar giovannigiovannisr?org.apache.commons.collections.comparators.ComparableComparator%n7xpcollections-generic-4.01/data/test/SynchronizedList.emptyCollection.version3.1.obj0000644000175000017500000000042510464140762030557 0ustar giovannigiovannisr4org.apache.commons.collections.list.SynchronizedList섓6DSxr@org.apache.commons.collections.collection.SynchronizedCollection!|rI "L collectiontLjava/util/Collection;LlocktLjava/lang/Object;xpsrjava.util.ArrayListxaIsizexpw xq~collections-generic-4.01/data/test/PredicatedBag.fullCollection.version3.1.obj0000644000175000017500000000072210464140763027527 0ustar giovannigiovannisr0org.apache.commons.collections.bag.PredicatedBag@gxr>org.apache.commons.collections.collection.PredicatedCollectionpvL predicatet*Lorg/apache/commons/collections/Predicate;xrQorg.apache.commons.collections.collection.AbstractSerializableCollectionDecoratorV4xpsr*org.apache.commons.collections.bag.HashBag-%jL comparatortLjava/util/Comparator;xppwxxcollections-generic-4.01/data/test/PredicatedSortedMap.fullCollection.version3.1.obj0000644000175000017500000000117710464140754030741 0ustar giovannigiovannisr6org.apache.commons.collections.map.PredicatedSortedMap.Kxr0org.apache.commons.collections.map.PredicatedMapfٟ%L keyPredicatet*Lorg/apache/commons/collections/Predicate;LvaluePredicateq~xpsr5org.apache.commons.collections.functors.TruePredicate.ՔQ&,xpq~srjava.util.TreeMap >-%jL comparatortLjava/util/Comparator;xppwtagaintagainvtalltallvtbartbarvtbaztbazvtblahtblahvtfootfoovtgeetgeevtgollytgollyvtgoodbyetgoodbyevtgoshtgoshvthellothellovtkeyptkey2tvaluet nonnullkeyq~!tseetseevttmpttmpvtwe'lltwe'llvtyoutyouvxxcollections-generic-4.01/data/test/IdentityMap.fullCollection.version3.obj0000644000175000017500000000030710464140762027137 0ustar giovannigiovannisr.org.apache.commons.collections.map.IdentityMap&$xpw ?@srjava.lang.Integer⠤8Ivaluexrjava.lang.Number xpsq~sq~q~sq~q~xcollections-generic-4.01/data/test/PredicatedList.fullCollection.version3.1.obj0000644000175000017500000000070610464140763027753 0ustar giovannigiovannisr2org.apache.commons.collections.list.PredicatedList;|&xr>org.apache.commons.collections.collection.PredicatedCollectionpvL predicatet*Lorg/apache/commons/collections/Predicate;xrQorg.apache.commons.collections.collection.AbstractSerializableCollectionDecoratorV4xpsrjava.util.ArrayListxaIsizexpw t1t3t5t7t2t4t6xxsr5org.apache.commons.collections.functors.TruePredicate.ՔQ&,xpcollections-generic-4.01/data/test/PredicatedSet.fullCollection.version3.1.obj0000644000175000017500000000067710464140761027600 0ustar giovannigiovannisr0org.apache.commons.collections.set.PredicatedSetYxr>org.apache.commons.collections.collection.PredicatedCollectionpvL predicatet*Lorg/apache/commons/collections/Predicate;xrQorg.apache.commons.collections.collection.AbstractSerializableCollectionDecoratorV4xpsrjava.util.HashSetD4xpw ?@t3t5t7t2t4t6t1xxsr5org.apache.commons.collections.functors.TruePredicate.ՔQ&,xpcollections-generic-4.01/data/test/ReferenceIdentityMap.fullCollection.version3.1.obj0000644000175000017500000000056610464140764031126 0ustar giovannigiovannisr7org.apache.commons.collections.map.ReferenceIdentityMapmxpw?@ tfootfoovtalltallvtgeetgeevtwe'lltwe'llvtseetseevtkeyt nonnullvaluetyoutyouvtbartbarvtgollytgollyvtgoshtgoshvtkey2tvaluetblahtblahvtgoodbyetgoodbyevttmpttmpvtbaztbazvt nonnullkeyq~thellothellovtagaintagainvpxcollections-generic-4.01/data/test/UnmodifiableSet.fullCollection.version3.1.obj0000644000175000017500000000113410464140756030123 0ustar giovannigiovannisr2org.apache.commons.collections.set.UnmodifiableSetZ1HaxrCorg.apache.commons.collections.set.AbstractSerializableSetDecoratorkxpsrjava.util.HashSetD4xpw ?@srjava.lang.Integer⠤8Ivaluexrjava.lang.Number xptThreepsrjava.lang.ShorthM74`RSvaluexq~ srjava.lang.ByteN`PBvaluexq~tEightsrjava.lang.DoubleJ)kDvaluexq~@srjava.lang.Floatɢ<Fvaluexq~@t14srjava.lang.Long;̏#Jvaluexq~ sq~tSeventNinetThirteent15sq~ ttOnexxcollections-generic-4.01/data/test/PredicatedList.emptyCollection.version3.1.obj0000644000175000017500000000065210464140757030152 0ustar giovannigiovannisr2org.apache.commons.collections.list.PredicatedList;|&xr>org.apache.commons.collections.collection.PredicatedCollectionpvL predicatet*Lorg/apache/commons/collections/Predicate;xrQorg.apache.commons.collections.collection.AbstractSerializableCollectionDecoratorV4xpsrjava.util.ArrayListxaIsizexpw xxsr5org.apache.commons.collections.functors.TruePredicate.ՔQ&,xpcollections-generic-4.01/data/test/UnmodifiableSortedMap.fullCollection.version3.1.obj0000644000175000017500000000064510464140763031272 0ustar giovannigiovannisr8org.apache.commons.collections.map.UnmodifiableSortedMapPXxpsrjava.util.TreeMap >-%jL comparatortLjava/util/Comparator;xppwtagaintagainvtalltallvtbartbarvtbaztbazvtblahtblahvtfootfoovtgeetgeevtgollytgollyvtgoodbyetgoodbyevtgoshtgoshvthellothellovtkeyptkey2tvaluet nonnullkeyq~tseetseevttmpttmpvtwe'lltwe'llvtyoutyouvxxcollections-generic-4.01/data/test/CursorableLinkedList.emptyCollection.version1.obj0000644000175000017500000000026310464140760031165 0ustar giovannigiovannisr3org.apache.commons.collections.CursorableLinkedListz,zI _modCountL_cursorstLjava/util/List;xpsrjava.util.ArrayListxaIsizexpw xwxcollections-generic-4.01/data/test/UnmodifiableCollection.emptyCollection.version3.1.obj0000644000175000017500000000035410464140762031657 0ustar giovannigiovannisr@org.apache.commons.collections.collection.UnmodifiableCollection};WxrQorg.apache.commons.collections.collection.AbstractSerializableCollectionDecoratorV4xpsrjava.util.ArrayListxaIsizexpw xxcollections-generic-4.01/data/test/UnmodifiableSet.emptyCollection.version3.1.obj0000644000175000017500000000031310464140761030311 0ustar giovannigiovannisr2org.apache.commons.collections.set.UnmodifiableSetZ1HaxrCorg.apache.commons.collections.set.AbstractSerializableSetDecoratorkxpsrjava.util.HashSetD4xpw ?@xxcollections-generic-4.01/data/test/SequencedHashMap.emptyCollection.version2.obj0000644000175000017500000000011310464140764030256 0ustar giovannigiovannisr/org.apache.commons.collections.SequencedHashMap.""& xpwxcollections-generic-4.01/data/test/SynchronizedSet.fullCollection.version3.1.obj0000644000175000017500000000123710464140756030210 0ustar giovannigiovannisr2org.apache.commons.collections.set.SynchronizedSetdb_xr@org.apache.commons.collections.collection.SynchronizedCollection!|rI "L collectiontLjava/util/Collection;LlocktLjava/lang/Object;xpsrjava.util.HashSetD4xpw ?@srjava.lang.Integer⠤8Ivaluexrjava.lang.Number xptThreepsrjava.lang.ShorthM74`RSvaluexq~ srjava.lang.ByteN`PBvaluexq~tEightsrjava.lang.DoubleJ)kDvaluexq~@srjava.lang.Floatɢ<Fvaluexq~@t14srjava.lang.Long;̏#Jvaluexq~ sq~tSeventNinetThirteent15sq~ ttOnexq~collections-generic-4.01/data/test/NodeCachingLinkedList.fullCollection.version3.obj0000644000175000017500000000100310464140763031030 0ustar giovannigiovannisr9org.apache.commons.collections.list.NodeCachingLinkedList_޶;? ImaximumCacheSizexpwttOnesrjava.lang.Integer⠤8Ivaluexrjava.lang.Number xptThreepsq~tOnesrjava.lang.DoubleJ)kDvaluexq~@srjava.lang.Floatɢ<Fvaluexq~@tSeventEighttNinesq~ srjava.lang.ShorthM74`RSvaluexq~ srjava.lang.Long;̏#Jvaluexq~ tThirteent14t15srjava.lang.ByteN`PBvaluexq~xcollections-generic-4.01/data/test/PredicatedSortedSet.emptyCollection.version3.1.obj0000644000175000017500000000074110464140763031147 0ustar giovannigiovannisr6org.apache.commons.collections.set.PredicatedSortedSeth_xr0org.apache.commons.collections.set.PredicatedSetYxr>org.apache.commons.collections.collection.PredicatedCollectionpvL predicatet*Lorg/apache/commons/collections/Predicate;xrQorg.apache.commons.collections.collection.AbstractSerializableCollectionDecoratorV4xpsrjava.util.TreeSetݘP[xppwxxsr5org.apache.commons.collections.functors.TruePredicate.ՔQ&,xpcollections-generic-4.01/data/test/CircularFifoBuffer.emptyCollection.version3.1.obj0000644000175000017500000000025410464140760030744 0ustar giovannigiovannisr8org.apache.commons.collections.buffer.CircularFifoBufferEZxr7org.apache.commons.collections.buffer.BoundedFifoBufferMl4Y I maxElementsxpdwxcollections-generic-4.01/data/test/TransformedSortedSet.fullCollection.version3.1.obj0000644000175000017500000000153010464140760031165 0ustar giovannigiovannisr7org.apache.commons.collections.set.TransformedSortedSetyGv^xr1org.apache.commons.collections.set.TransformedSet?;xr?org.apache.commons.collections.collection.TransformedCollectionx@sL transformert,Lorg/apache/commons/collections/Transformer;xrQorg.apache.commons.collections.collection.AbstractSerializableCollectionDecoratorV4xpsrjava.util.TreeSetݘP[xppwsrjava.lang.Integer⠤8Ivaluexrjava.lang.Number xpsq~sq~sq~sq~ sq~ sq~ sq~sq~sq~sq~sq~sq~sq~sq~sq~sq~!sq~#sq~%sq~'sq~)sq~+sq~-sq~/sq~1sq~3sq~5sq~7sq~9sq~;xxsr6org.apache.commons.collections.functors.NOPTransformer=?wxpcollections-generic-4.01/data/test/LazyMap.emptyCollection.version3.1.obj0000644000175000017500000000066210464140754026625 0ustar giovannigiovannisr*org.apache.commons.collections.map.LazyMapn唂yLfactoryt,Lorg/apache/commons/collections/Transformer;xpsr:org.apache.commons.collections.functors.FactoryTransformerb)]LiFactoryt(Lorg/apache/commons/collections/Factory;xpsr7org.apache.commons.collections.functors.ConstantFactory$ m[*L iConstanttLjava/lang/Object;xppsrjava.util.HashMap`F loadFactorI thresholdxp?@wxxcollections-generic-4.01/data/test/ReverseComparator.version2.obj0000644000175000017500000000025710464140761025400 0ustar giovannigiovannisr-%jL comparatortLjava/util/Comparator;xppwxsq~pwxcollections-generic-4.01/data/test/LinkedMap.fullCollection.version3.obj0000644000175000017500000000051310464140762026553 0ustar giovannigiovannisr,org.apache.commons.collections.map.LinkedMap}І$vGjxpw ?@ tagaintblahvtalltfoovtbartbarvtbaztbazvtblahttmpvtfootgoshvtgeetgollyvtgollytgeevtgoodbyethellovtgoshtgoodbyevthellotwe'llvtkeytseevtkey2tyouvtseetallvttmptagainvtwe'llptyoutvaluepq~"xcollections-generic-4.01/data/test/TransformedSet.fullCollection.version3.1.obj0000644000175000017500000000147310464140763030015 0ustar giovannigiovannisr1org.apache.commons.collections.set.TransformedSet?;xr?org.apache.commons.collections.collection.TransformedCollectionx@sL transformert,Lorg/apache/commons/collections/Transformer;xrQorg.apache.commons.collections.collection.AbstractSerializableCollectionDecoratorV4xpsrjava.util.HashSetD4xpw ?@srjava.lang.Integer⠤8Ivaluexrjava.lang.Number xptThreepsrjava.lang.ShorthM74`RSvaluexq~ srjava.lang.ByteN`PBvaluexq~tEightsrjava.lang.DoubleJ)kDvaluexq~@srjava.lang.Floatɢ<Fvaluexq~@t14srjava.lang.Long;̏#Jvaluexq~ sq~tSeventNinetThirteent15sq~ ttOnexxsr6org.apache.commons.collections.functors.NOPTransformer=?wxpcollections-generic-4.01/data/test/HashedMap.fullCollection.version3.obj0000644000175000017500000000051310464140761026540 0ustar giovannigiovannisr,org.apache.commons.collections.map.HashedMap/ FOsxpw ?@ tfootfoovtwe'lltwe'llvtseetseevtbaztbazvthellothellovtbartbarvtagaintagainvtkey2tvaluepq~tgoodbyetgoodbyevtkeyptyoutyouvtblahtblahvtgeetgeevttmpttmpvtgollytgollyvtgoshtgoshvtalltallvxcollections-generic-4.01/data/test/TransformedBag.emptyCollection.version3.1.obj0000644000175000017500000000067310464140763030150 0ustar giovannigiovannisr1org.apache.commons.collections.bag.TransformedBagK;8xxr?org.apache.commons.collections.collection.TransformedCollectionx@sL transformert,Lorg/apache/commons/collections/Transformer;xrQorg.apache.commons.collections.collection.AbstractSerializableCollectionDecoratorV4xpsr*org.apache.commons.collections.bag.HashBag-%jL comparatortLjava/util/Comparator;xppwxxcollections-generic-4.01/data/test/TransformedCollection.fullCollection.version3.1.obj0000644000175000017500000000061310464140764031351 0ustar giovannigiovannisr?org.apache.commons.collections.collection.TransformedCollectionx@sL transformert,Lorg/apache/commons/collections/Transformer;xrQorg.apache.commons.collections.collection.AbstractSerializableCollectionDecoratorV4xpsrjava.util.ArrayListxaIsizexpw t1t3t5t7t2t4t6xxsr6org.apache.commons.collections.functors.NOPTransformer=?wxpcollections-generic-4.01/data/test/DualTreeBidiMap.fullCollection.version3.obj0000644000175000017500000000071010464140755027643 0ustar giovannigiovannisr6org.apache.commons.collections.bidimap.DualTreeBidiMap[QL comparatortLjava/util/Comparator;xppsrjava.util.TreeMap >-%jL comparatorq~xppwtagaintagainvtalltallvtbartbarvtbaztbazvtblahtblahvtfootfoovtgeetgeevtgollytgollyvtgoodbyetgoodbyevtgoshtgoshvthellothellovtkeyt nonnullvaluetkey2tvaluet nonnullkeytvalue2tseetseevttmpttmpvtwe'lltwe'llvtyoutyouvxxcollections-generic-4.01/data/test/PredicatedSortedMap.emptyCollection.version3.1.obj0000644000175000017500000000057010464140757031134 0ustar giovannigiovannisr6org.apache.commons.collections.map.PredicatedSortedMap.Kxr0org.apache.commons.collections.map.PredicatedMapfٟ%L keyPredicatet*Lorg/apache/commons/collections/Predicate;LvaluePredicateq~xpsr5org.apache.commons.collections.functors.TruePredicate.ՔQ&,xpq~srjava.util.TreeMap >-%jL comparatortLjava/util/Comparator;xppwxxcollections-generic-4.01/data/test/SynchronizedCollection.emptyCollection.version3.1.obj0000644000175000017500000000032210464140763031734 0ustar giovannigiovannisr@org.apache.commons.collections.collection.SynchronizedCollection!|rI "L collectiontLjava/util/Collection;LlocktLjava/lang/Object;xpsrjava.util.ArrayListxaIsizexpw xq~collections-generic-4.01/data/test/NullComparator.version2.obj10000644000175000017500000000033310464140756024757 0ustar giovannigiovannisr9org.apache.commons.collections.comparators.NullComparator8v.Y-Z nullsAreHighLnonNullComparatortLjava/util/Comparator;xpsr?org.apache.commons.collections.comparators.ComparableComparator%n7xpcollections-generic-4.01/data/test/LRUMap.emptyCollection.version3.obj0000644000175000017500000000012110464140757026202 0ustar giovannigiovannisr)org.apache.commons.collections.map.LRUMapTxpwd?@xcollections-generic-4.01/data/test/TransformedSortedMap.emptyCollection.version3.1.obj0000644000175000017500000000060110464140757031347 0ustar giovannigiovannisr7org.apache.commons.collections.map.TransformedSortedMapvx;xr1org.apache.commons.collections.map.TransformedMapaw?]ZpLkeyTransformert,Lorg/apache/commons/collections/Transformer;LvalueTransformerq~xpsr6org.apache.commons.collections.functors.NOPTransformer=?wxpq~srjava.util.TreeMap >-%jL comparatortLjava/util/Comparator;xppwxxcollections-generic-4.01/data/test/PredicatedSortedBag.emptyCollection.version3.1.obj0000644000175000017500000000077210464140756031113 0ustar giovannigiovannisr6org.apache.commons.collections.bag.PredicatedSortedBag/o +xr0org.apache.commons.collections.bag.PredicatedBag@gxr>org.apache.commons.collections.collection.PredicatedCollectionpvL predicatet*Lorg/apache/commons/collections/Predicate;xrQorg.apache.commons.collections.collection.AbstractSerializableCollectionDecoratorV4xpsr*org.apache.commons.collections.bag.TreeBagylxppwxxsr5org.apache.commons.collections.functors.TruePredicate.ՔQ&,xpcollections-generic-4.01/data/test/SingletonMap.emptyCollection.version3.1.obj0000644000175000017500000000035410464140762027645 0ustar giovannigiovannisr1org.apache.commons.collections.map.ListOrderedMap%o53fL insertOrdertLjava/util/List;xpsrjava.util.ArrayListxaIsizexpw xsrjava.util.HashMap`F loadFactorI thresholdxp?@wxxcollections-generic-4.01/data/test/MultiKeyMap.fullCollection.version3.1.obj0000644000175000017500000000167010464140762027254 0ustar giovannigiovannisr.org.apache.commons.collections.map.MultiKeyMap/ FOsLmapt6Lorg/apache/commons/collections/map/AbstractHashedMap;xpsr,org.apache.commons.collections.map.HashedMap/ FOsxpw ?@ sr0org.apache.commons.collections.keyvalue.MultiKey=uwIhashCode[keyst[Ljava/lang/Object;xpur[Ljava.lang.Object;Xs)lxpsrjava.lang.Integer⠤8Ivaluexrjava.lang.Number xpsq~ sq~ sq~ sq~ t5Lsq~uq~sq~ sq~ t2Asq~uq~q~ sq~ t2Csq~uq~q~q~q~t3Dsq~uq~q~ q~q~t3Fsq~uq~q~q~ q~q~ q~t5Ksq~uq~q~q~ t2Bsq~uq~q~q~q~q~ t4Gsq~ uq~q~ q~q~q~t4Isq~uq~q~q~ q~t3Esq~uq~q~q~q~ q~t4Hsq~uq~q~q~q~q~ q~t5Jxcollections-generic-4.01/data/test/MultiKeyMap.emptyCollection.version3.1.obj0000644000175000017500000000031610464140757027450 0ustar giovannigiovannisr.org.apache.commons.collections.map.MultiKeyMap/ FOsLmapt6Lorg/apache/commons/collections/map/AbstractHashedMap;xpsr,org.apache.commons.collections.map.HashedMap/ FOsxpw ?@xcollections-generic-4.01/data/test/DualTreeBidiMap.fullCollection.version3.Test2.obj0000644000175000017500000000117210464140760030642 0ustar giovannigiovannisr6org.apache.commons.collections.bidimap.DualTreeBidiMap[QL comparatortLjava/util/Comparator;xpsr-%jL comparatorq~xpq~wtyoutyouvtwe'lltwe'llvttmpttmpvtseetseevt nonnullkeytvalue2tkey2tvaluetkeyt nonnullvaluethellothellovtgoshtgoshvtgoodbyetgoodbyevtgollytgollyvtgeetgeevtfootfoovtblahtblahvtbaztbazvtbartbarvtalltallvtagaintagainvxxcollections-generic-4.01/data/test/TransformedSortedBag.emptyCollection.version3.1.obj0000644000175000017500000000100210464140756031316 0ustar giovannigiovannisr7org.apache.commons.collections.bag.TransformedSortedBagXݶxr1org.apache.commons.collections.bag.TransformedBagK;8xxr?org.apache.commons.collections.collection.TransformedCollectionx@sL transformert,Lorg/apache/commons/collections/Transformer;xrQorg.apache.commons.collections.collection.AbstractSerializableCollectionDecoratorV4xpsr*org.apache.commons.collections.bag.TreeBagylxppwxxsr6org.apache.commons.collections.functors.NOPTransformer=?wxpcollections-generic-4.01/data/test/UnboundedFifoBuffer.fullCollection.version3.1.obj0000644000175000017500000000075310464140754030736 0ustar giovannigiovannisr9org.apache.commons.collections.buffer.UnboundedFifoBufferϪ fUxpwttOnesrjava.lang.Integer⠤8Ivaluexrjava.lang.Number xptThreesq~tOnesrjava.lang.DoubleJ)kDvaluexq~@srjava.lang.Floatɢ<Fvaluexq~@tSeventEighttNinesq~ srjava.lang.ShorthM74`RSvaluexq~ srjava.lang.Long;̏#Jvaluexq~ tThirteent14t15srjava.lang.ByteN`PBvaluexq~xcollections-generic-4.01/data/test/MultiHashMap.fullCollection.version2.obj0000644000175000017500000000141110464140761027237 0ustar giovannigiovannisr+org.apache.commons.collections.MultiHashMap LmNametLjava/lang/String;xrjava.util.HashMap`F loadFactorI thresholdxp?@#w/tgollysrjava.util.ArrayListxaIsizexpw tgollyvxtgoodbyesq~w tgoodbyevxtallsq~w tallvxtblahsq~w tblahvxtgeesq~w tgeevxtyousq~w tyouvxtagainsq~w tagainvxthellosq~w thellovxtwe'llsq~w twe'llvxtbazsq~w tbazvxtgoshsq~w tgoshvxtbarsq~w tbarvxtfoosq~w tfoovxtseesq~w tseevxttmpsq~w ttmpvxtkey2sq~w tvaluexpsq~w q~4xtkeysq~w pxxt MultiMap-28collections-generic-4.01/data/test/TransformedSortedSet.emptyCollection.version3.1.obj0000644000175000017500000000075110464140763031370 0ustar giovannigiovannisr7org.apache.commons.collections.set.TransformedSortedSetyGv^xr1org.apache.commons.collections.set.TransformedSet?;xr?org.apache.commons.collections.collection.TransformedCollectionx@sL transformert,Lorg/apache/commons/collections/Transformer;xrQorg.apache.commons.collections.collection.AbstractSerializableCollectionDecoratorV4xpsrjava.util.TreeSetݘP[xppwxxsr6org.apache.commons.collections.functors.NOPTransformer=?wxpcollections-generic-4.01/data/test/BooleanComparator.version3.obj0000644000175000017500000000013610464140757025346 0ustar giovannigiovannisr collections-generic-4.01/src/0000755000175000017500000000000010464140764016371 5ustar giovannigiovannicollections-generic-4.01/src/java/0000755000175000017500000000000010464140753017310 5ustar giovannigiovannicollections-generic-4.01/src/java/org/0000755000175000017500000000000010464140753020077 5ustar giovannigiovannicollections-generic-4.01/src/java/org/apache/0000755000175000017500000000000010464140753021320 5ustar giovannigiovannicollections-generic-4.01/src/java/org/apache/commons/0000755000175000017500000000000010464140753022773 5ustar giovannigiovannicollections-generic-4.01/src/java/org/apache/commons/collections15/0000755000175000017500000000000011664401370025455 5ustar giovannigiovannicollections-generic-4.01/src/java/org/apache/commons/collections15/IterableMap.java0000644000175000017500000000364110464140762030513 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15; import java.util.Map; /** * Defines a map that can be iterated directly without needing to create an entry set. *

* A map iterator is an efficient way of iterating over maps. * There is no need to access the entry set or cast to Map Entry objects. *

 * IterableMap map = new HashedMap();
 * MapIterator it = map.mapIterator();
 * while (it.hasNext()) {
 *   Object key = it.next();
 *   Object value = it.getValue();
 *   it.setValue("newValue");
 * }
 * 
* * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:19 $ * @since Commons Collections 3.0 */ public interface IterableMap extends Map { /** * Obtains a MapIterator over the map. *

* A map iterator is an efficient way of iterating over maps. * There is no need to access the entry set or cast to Map Entry objects. *

     * IterableMap map = new HashedMap();
     * MapIterator it = map.mapIterator();
     * while (it.hasNext()) {
     *   Object key = it.next();
     *   Object value = it.getValue();
     *   it.setValue("newValue");
     * }
     * 
* * @return a map iterator */ MapIterator mapIterator(); } collections-generic-4.01/src/java/org/apache/commons/collections15/ExtendedProperties.java0000644000175000017500000015564110464140757032157 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15; import java.io.*; import java.util.*; /** * This class extends normal Java properties by adding the possibility * to use the same key many times concatenating the value strings * instead of overwriting them. *

* Please consider using the PropertiesConfiguration class in * Commons-Configuration as soon as it is released. *

* The Extended Properties syntax is explained here: *

*

    *
  • * Each property has the syntax key = value *
  • *
  • * The key may use any character but the equal sign '='. *
  • *
  • * value may be separated on different lines if a backslash * is placed at the end of the line that continues below. *
  • *
  • * If value is a list of strings, each token is separated * by a comma ','. *
  • *
  • * Commas in each token are escaped placing a backslash right before * the comma. *
  • *
  • * Backslashes are escaped by using two consecutive backslashes i.e. \\ *
  • *
  • * If a key is used more than once, the values are appended * like if they were on the same line separated with commas. *
  • *
  • * Blank lines and lines starting with character '#' are skipped. *
  • *
  • * If a property is named "include" (or whatever is defined by * setInclude() and getInclude() and the value of that property is * the full path to a file on disk, that file will be included into * the ConfigurationsRepository. You can also pull in files relative * to the parent configuration file. So if you have something * like the following: *

    * include = additional.properties *

    * Then "additional.properties" is expected to be in the same * directory as the parent configuration file. *

    * Duplicate name values will be replaced, so be careful. *

    *

  • *
*

*

Here is an example of a valid extended properties file: *

*

 *      # lines starting with # are comments
 * 

* # This is the simplest property * key = value *

* # A long property may be separated on multiple lines * longvalue = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \ * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *

* # This is a property with many tokens * tokens_on_a_line = first token, second token *

* # This sequence generates exactly the same result * tokens_on_multiple_lines = first token * tokens_on_multiple_lines = second token *

* # commas may be escaped in tokens * commas.escaped = Hi\, what'up? *

*

*

NOTE: this class has not been written for * performance nor low memory usage. In fact, it's way slower than it * could be and generates too much memory garbage. But since * performance is not an issue during intialization (and there is not * much time to improve it), I wrote it this way. If you don't like * it, go ahead and tune it up! * * @author Stefano Mazzocchi * @author Jon S. Stevens * @author Dave Bryson * @author Jason van Zyl * @author Geir Magnusson Jr. * @author Leon Messerschmidt * @author Kent Johnson * @author Daniel Rall * @author Ilkka Priha * @author Janek Bogucki * @author Mohan Kishore * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:19 $ * @since Commons Collections 1.0 */ public class ExtendedProperties extends Hashtable { /** * Default configurations repository. */ private ExtendedProperties defaults; /** * The file connected to this repository (holding comments and * such). * * @serial */ protected String file; /** * Base path of the configuration file used to create * this ExtendedProperties object. */ protected String basePath; /** * File separator. */ protected String fileSeparator = System.getProperty("file.separator"); /** * Has this configuration been intialized. */ protected boolean isInitialized = false; /** * This is the name of the property that can point to other * properties file for including other properties files. */ protected static String include = "include"; /** * These are the keys in the order they listed * in the configuration file. This is useful when * you wish to perform operations with configuration * information in a particular order. */ protected ArrayList keysAsListed = new ArrayList(); protected final static String START_TOKEN = "${"; protected final static String END_TOKEN = "}"; /** * Interpolate key names to handle ${key} stuff * * @param base string to interpolate * @return returns the key name with the ${key} substituted */ protected String interpolate(String base) { // COPIED from [configuration] 2003-12-29 return (interpolateHelper(base, null)); } /** * Recursive handler for multiple levels of interpolation. *

* When called the first time, priorVariables should be null. * * @param base string with the ${key} variables * @param priorVariables serves two purposes: to allow checking for * loops, and creating a meaningful exception message should a loop * occur. It's 0'th element will be set to the value of base from * the first call. All subsequent interpolated variables are added * afterward. * @return the string with the interpolation taken care of */ protected String interpolateHelper(String base, List priorVariables) { // COPIED from [configuration] 2003-12-29 if (base == null) { return null; } // on the first call initialize priorVariables // and add base as the first element if (priorVariables == null) { priorVariables = new ArrayList(); priorVariables.add(base); } int begin = -1; int end = -1; int prec = 0 - END_TOKEN.length(); String variable = null; StringBuffer result = new StringBuffer(); // FIXME: we should probably allow the escaping of the start token while (((begin = base.indexOf(START_TOKEN, prec + END_TOKEN.length())) > -1) && ((end = base.indexOf(END_TOKEN, begin)) > -1)) { result.append(base.substring(prec + END_TOKEN.length(), begin)); variable = base.substring(begin + START_TOKEN.length(), end); // if we've got a loop, create a useful exception message and throw if (priorVariables.contains(variable)) { String initialBase = priorVariables.remove(0).toString(); priorVariables.add(variable); StringBuffer priorVariableSb = new StringBuffer(); // create a nice trace of interpolated variables like so: // var1->var2->var3 for (Iterator it = priorVariables.iterator(); it.hasNext();) { priorVariableSb.append(it.next()); if (it.hasNext()) { priorVariableSb.append("->"); } } throw new IllegalStateException("infinite loop in property interpolation of " + initialBase + ": " + priorVariableSb.toString()); } // otherwise, add this variable to the interpolation list. else { priorVariables.add(variable); } //QUESTION: getProperty or getPropertyDirect Object value = getProperty(variable); if (value != null) { result.append(interpolateHelper(value.toString(), priorVariables)); // pop the interpolated variable off the stack // this maintains priorVariables correctness for // properties with multiple interpolations, e.g. // prop.name=${some.other.prop1}/blahblah/${some.other.prop2} priorVariables.remove(priorVariables.size() - 1); } else if (defaults != null && defaults.getString(variable, null) != null) { result.append(defaults.getString(variable)); } else { //variable not defined - so put it back in the value result.append(START_TOKEN).append(variable).append(END_TOKEN); } prec = end; } result.append(base.substring(prec + END_TOKEN.length(), base.length())); return result.toString(); } /** * Inserts a backslash before every comma and backslash. */ private static String escape(String s) { StringBuffer buf = new StringBuffer(s); for (int i = 0; i < buf.length(); i++) { char c = buf.charAt(i); if (c == ',' || c == '\\') { buf.insert(i, '\\'); i++; } } return buf.toString(); } /** * Removes a backslash from every pair of backslashes. */ private static String unescape(String s) { StringBuffer buf = new StringBuffer(s); for (int i = 0; i < buf.length() - 1; i++) { char c1 = buf.charAt(i); char c2 = buf.charAt(i + 1); if (c1 == '\\' && c2 == '\\') { buf.deleteCharAt(i); } } return buf.toString(); } /** * Counts the number of successive times 'ch' appears in the * 'line' before the position indicated by the 'index'. */ private static int countPreceding(String line, int index, char ch) { int i; for (i = index - 1; i >= 0; i--) { if (line.charAt(i) != ch) { break; } } return index - 1 - i; } /** * Checks if the line ends with odd number of backslashes */ private static boolean endsWithSlash(String line) { if (!line.endsWith("\\")) { return false; } return (countPreceding(line, line.length() - 1, '\\') % 2 == 0); } /** * This class is used to read properties lines. These lines do * not terminate with new-line chars but rather when there is no * backslash sign a the end of the line. This is used to * concatenate multiple lines for readability. */ static class PropertiesReader extends LineNumberReader { /** * Constructor. * * @param reader A Reader. */ public PropertiesReader(Reader reader) { super(reader); } /** * Read a property. * * @return a String property * @throws IOException if there is difficulty reading the source. */ public String readProperty() throws IOException { StringBuffer buffer = new StringBuffer(); try { while (true) { String line = readLine().trim(); if ((line.length() != 0) && (line.charAt(0) != '#')) { if (endsWithSlash(line)) { line = line.substring(0, line.length() - 1); buffer.append(line); } else { buffer.append(line); break; } } } } catch (NullPointerException ex) { return null; } return buffer.toString(); } } /** * This class divides into tokens a property value. Token * separator is "," but commas into the property value are escaped * using the backslash in front. */ static class PropertiesTokenizer extends StringTokenizer { /** * The property delimiter used while parsing (a comma). */ static final String DELIMITER = ","; /** * Constructor. * * @param string A String. */ public PropertiesTokenizer(String string) { super(string, DELIMITER); } /** * Check whether the object has more tokens. * * @return True if the object has more tokens. */ public boolean hasMoreTokens() { return super.hasMoreTokens(); } /** * Get next token. * * @return A String. */ public String nextToken() { StringBuffer buffer = new StringBuffer(); while (hasMoreTokens()) { String token = super.nextToken(); if (endsWithSlash(token)) { buffer.append(token.substring(0, token.length() - 1)); buffer.append(DELIMITER); } else { buffer.append(token); break; } } return buffer.toString().trim(); } } /** * Creates an empty extended properties object. */ public ExtendedProperties() { super(); } /** * Creates and loads the extended properties from the specified file. * * @param file the filename to load * @throws IOException if a file error occurs */ public ExtendedProperties(String file) throws IOException { this(file, null); } /** * Creates and loads the extended properties from the specified file. * * @param file the filename to load * @param defaultFile a second filename to load default values from * @throws IOException if a file error occurs */ public ExtendedProperties(String file, String defaultFile) throws IOException { this.file = file; basePath = new File(file).getAbsolutePath(); basePath = basePath.substring(0, basePath.lastIndexOf(fileSeparator) + 1); FileInputStream in = null; try { in = new FileInputStream(file); this.load(in); } finally { try { if (in != null) { in.close(); } } catch (IOException ex) { } } if (defaultFile != null) { defaults = new ExtendedProperties(defaultFile); } } /** * Indicate to client code whether property * resources have been initialized or not. */ public boolean isInitialized() { return isInitialized; } /** * Gets the property value for including other properties files. * By default it is "include". * * @return A String. */ public String getInclude() { return include; } /** * Sets the property value for including other properties files. * By default it is "include". * * @param inc A String. */ public void setInclude(String inc) { include = inc; } /** * Load the properties from the given input stream. * * @param input the InputStream to load from * @throws IOException if an IO error occurs */ public void load(InputStream input) throws IOException { load(input, null); } /** * Load the properties from the given input stream * and using the specified encoding. * * @param input the InputStream to load from * @param enc the encoding to use * @throws IOException if an IO error occurs */ public synchronized void load(InputStream input, String enc) throws IOException { PropertiesReader reader = null; if (enc != null) { try { reader = new PropertiesReader(new InputStreamReader(input, enc)); } catch (UnsupportedEncodingException ex) { // Another try coming up.... } } if (reader == null) { try { reader = new PropertiesReader(new InputStreamReader(input, "8859_1")); } catch (UnsupportedEncodingException ex) { // ISO8859-1 support is required on java platforms but.... // If it's not supported, use the system default encoding reader = new PropertiesReader(new InputStreamReader(input)); } } try { while (true) { String line = reader.readProperty(); int equalSign = line.indexOf('='); if (equalSign > 0) { String key = line.substring(0, equalSign).trim(); String value = line.substring(equalSign + 1).trim(); // Configure produces lines like this ... just ignore them if ("".equals(value)) { continue; } if (getInclude() != null && key.equalsIgnoreCase(getInclude())) { // Recursively load properties files. File file = null; if (value.startsWith(fileSeparator)) { // We have an absolute path so we'll use this file = new File(value); } else { // We have a relative path, and we have two // possible forms here. If we have the "./" form // then just strip that off first before continuing. if (value.startsWith("." + fileSeparator)) { value = value.substring(2); } file = new File(basePath + value); } if (file != null && file.exists() && file.canRead()) { load(new FileInputStream(file)); } } else { addProperty(key, value); } } } } catch (NullPointerException ex) { // Should happen only when EOF is reached. return; } finally { // Loading is initializing isInitialized = true; } } /** * Gets a property from the configuration. * * @param key property to retrieve * @return value as object. Will return user value if exists, * if not then default value if exists, otherwise null */ public Object getProperty(String key) { // first, try to get from the 'user value' store Object obj = this.get(key); if (obj == null) { // if there isn't a value there, get it from the // defaults if we have them if (defaults != null) { obj = defaults.get(key); } } return obj; } /** * Add a property to the configuration. If it already * exists then the value stated here will be added * to the configuration entry. For example, if *

* resource.loader = file *

* is already present in the configuration and you *

* addProperty("resource.loader", "classpath") *

* Then you will end up with a Vector like the * following: *

* ["file", "classpath"] * * @param key the key to add * @param value the value to add */ public void addProperty(String key, Object value) { if (value instanceof String) { String str = (String) value; if (str.indexOf(PropertiesTokenizer.DELIMITER) > 0) { // token contains commas, so must be split apart then added PropertiesTokenizer tokenizer = new PropertiesTokenizer(str); while (tokenizer.hasMoreTokens()) { String token = tokenizer.nextToken(); addPropertyInternal(key, unescape(token)); } } else { // token contains no commas, so can be simply added addPropertyInternal(key, unescape(str)); } } else { addPropertyInternal(key, value); } // Adding a property connotes initialization isInitialized = true; } /** * Adds a key/value pair to the map. This routine does * no magic morphing. It ensures the keylist is maintained * * @param key the key to store at * @param value the decoded object to store */ private void addPropertyDirect(String key, Object value) { // safety check if (!containsKey(key)) { keysAsListed.add(key); } put(key, value); } /** * Adds a decoded property to the map w/o checking for commas - used * internally when a property has been broken up into * strings that could contain escaped commas to prevent * the inadvertent vectorization. *

* Thanks to Leon Messerschmidt for this one. * * @param key the key to store at * @param value the decoded object to store */ private void addPropertyInternal(String key, Object value) { Object current = this.get(key); if (current instanceof String) { // one object already in map - convert it to a vector Vector v = new Vector(2); v.addElement(current); v.addElement(value); put(key, v); } else if (current instanceof Vector) { // already a vector - just add the new token ((Vector) current).addElement(value); } else { // brand new key - store in keysAsListed to retain order if (!containsKey(key)) { keysAsListed.add(key); } put(key, value); } } /** * Set a property, this will replace any previously * set values. Set values is implicitly a call * to clearProperty(key), addProperty(key,value). * * @param key the key to set * @param value the value to set */ public void setProperty(String key, Object value) { clearProperty(key); addProperty(key, value); } /** * Save the properties to the given output stream. *

* The stream is not closed, but it is flushed. * * @param output an OutputStream, may be null * @param header a textual comment to act as a file header * @throws IOException if an IO error occurs */ public synchronized void save(OutputStream output, String header) throws IOException { if (output == null) { return; } PrintWriter theWrtr = new PrintWriter(output); if (header != null) { theWrtr.println(header); } Enumeration theKeys = keys(); while (theKeys.hasMoreElements()) { String key = (String) theKeys.nextElement(); Object value = get(key); if (value != null) { if (value instanceof String) { StringBuffer currentOutput = new StringBuffer(); currentOutput.append(key); currentOutput.append("="); currentOutput.append(escape((String) value)); theWrtr.println(currentOutput.toString()); } else if (value instanceof Vector) { Vector values = (Vector) value; Enumeration valuesEnum = values.elements(); while (valuesEnum.hasMoreElements()) { String currentElement = (String) valuesEnum.nextElement(); StringBuffer currentOutput = new StringBuffer(); currentOutput.append(key); currentOutput.append("="); currentOutput.append(escape(currentElement)); theWrtr.println(currentOutput.toString()); } } } theWrtr.println(); theWrtr.flush(); } } /** * Combines an existing Hashtable with this Hashtable. *

* Warning: It will overwrite previous entries without warning. * * @param props the properties to combine */ public void combine(ExtendedProperties props) { for (Iterator it = props.getKeys(); it.hasNext();) { String key = (String) it.next(); setProperty(key, props.get(key)); } } /** * Clear a property in the configuration. * * @param key the property key to remove along with corresponding value */ public void clearProperty(String key) { if (containsKey(key)) { // we also need to rebuild the keysAsListed or else // things get *very* confusing for (int i = 0; i < keysAsListed.size(); i++) { if ((keysAsListed.get(i)).equals(key)) { keysAsListed.remove(i); break; } } remove(key); } } /** * Get the list of the keys contained in the configuration * repository. * * @return an Iterator over the keys */ public Iterator getKeys() { return keysAsListed.iterator(); } /** * Get the list of the keys contained in the configuration * repository that match the specified prefix. * * @param prefix the prefix to match * @return an Iterator of keys that match the prefix */ public Iterator getKeys(String prefix) { Iterator keys = getKeys(); ArrayList matchingKeys = new ArrayList(); while (keys.hasNext()) { Object key = keys.next(); if (key instanceof String && ((String) key).startsWith(prefix)) { matchingKeys.add(key); } } return matchingKeys.iterator(); } /** * Create an ExtendedProperties object that is a subset * of this one. Take into account duplicate keys * by using the setProperty() in ExtendedProperties. * * @param prefix the prefix to get a subset for * @return a new independent ExtendedProperties */ public ExtendedProperties subset(String prefix) { ExtendedProperties c = new ExtendedProperties(); Iterator keys = getKeys(); boolean validSubset = false; while (keys.hasNext()) { Object key = keys.next(); if (key instanceof String && ((String) key).startsWith(prefix)) { if (!validSubset) { validSubset = true; } /* * Check to make sure that c.subset(prefix) doesn't * blow up when there is only a single property * with the key prefix. This is not a useful * subset but it is a valid subset. */ String newKey = null; if (((String) key).length() == prefix.length()) { newKey = prefix; } else { newKey = ((String) key).substring(prefix.length() + 1); } /* * use addPropertyDirect() - this will plug the data as * is into the Map, but will also do the right thing * re key accounting */ c.addPropertyDirect(newKey, get(key)); } } if (validSubset) { return c; } else { return null; } } /** * Display the configuration for debugging purposes to System.out. */ public void display() { Iterator i = getKeys(); while (i.hasNext()) { String key = (String) i.next(); Object value = get(key); System.out.println(key + " => " + value); } } /** * Get a string associated with the given configuration key. * * @param key The configuration key. * @return The associated string. * @throws ClassCastException is thrown if the key maps to an * object that is not a String. */ public String getString(String key) { return getString(key, null); } /** * Get a string associated with the given configuration key. * * @param key The configuration key. * @param defaultValue The default value. * @return The associated string if key is found, * default value otherwise. * @throws ClassCastException is thrown if the key maps to an * object that is not a String. */ public String getString(String key, String defaultValue) { Object value = get(key); if (value instanceof String) { return interpolate((String) value); } else if (value == null) { if (defaults != null) { return interpolate(defaults.getString(key, defaultValue)); } else { return interpolate(defaultValue); } } else if (value instanceof Vector) { return interpolate((String) ((Vector) value).get(0)); } else { throw new ClassCastException('\'' + key + "' doesn't map to a String object"); } } /** * Get a list of properties associated with the given * configuration key. * * @param key The configuration key. * @return The associated properties if key is found. * @throws ClassCastException is thrown if the key maps to an * object that is not a String/Vector. * @throws IllegalArgumentException if one of the tokens is * malformed (does not contain an equals sign). */ public Properties getProperties(String key) { return getProperties(key, new Properties()); } /** * Get a list of properties associated with the given * configuration key. * * @param key The configuration key. * @return The associated properties if key is found. * @throws ClassCastException is thrown if the key maps to an * object that is not a String/Vector. * @throws IllegalArgumentException if one of the tokens is * malformed (does not contain an equals sign). */ public Properties getProperties(String key, Properties defaults) { /* * Grab an array of the tokens for this key. */ String[] tokens = getStringArray(key); // Each token is of the form 'key=value'. Properties props = new Properties(defaults); for (int i = 0; i < tokens.length; i++) { String token = tokens[i]; int equalSign = token.indexOf('='); if (equalSign > 0) { String pkey = token.substring(0, equalSign).trim(); String pvalue = token.substring(equalSign + 1).trim(); props.put(pkey, pvalue); } else { throw new IllegalArgumentException('\'' + token + "' does not contain " + "an equals sign"); } } return props; } /** * Get an array of strings associated with the given configuration * key. * * @param key The configuration key. * @return The associated string array if key is found. * @throws ClassCastException is thrown if the key maps to an * object that is not a String/Vector. */ public String[] getStringArray(String key) { Object value = get(key); // What's your vector, Victor? Vector vector; if (value instanceof String) { vector = new Vector(1); vector.addElement(value); } else if (value instanceof Vector) { vector = (Vector) value; } else if (value == null) { if (defaults != null) { return defaults.getStringArray(key); } else { return new String[0]; } } else { throw new ClassCastException('\'' + key + "' doesn't map to a String/Vector object"); } String[] tokens = new String[vector.size()]; for (int i = 0; i < tokens.length; i++) { tokens[i] = (String) vector.elementAt(i); } return tokens; } /** * Get a Vector of strings associated with the given configuration * key. * * @param key The configuration key. * @return The associated Vector. * @throws ClassCastException is thrown if the key maps to an * object that is not a Vector. */ public Vector getVector(String key) { return getVector(key, null); } /** * Get a Vector of strings associated with the given configuration * key. * * @param key The configuration key. * @param defaultValue The default value. * @return The associated Vector. * @throws ClassCastException is thrown if the key maps to an * object that is not a Vector. */ public Vector getVector(String key, Vector defaultValue) { Object value = get(key); if (value instanceof Vector) { return (Vector) value; } else if (value instanceof String) { Vector v = new Vector(1); v.addElement(value); put(key, v); return v; } else if (value == null) { if (defaults != null) { return defaults.getVector(key, defaultValue); } else { return ((defaultValue == null) ? new Vector() : defaultValue); } } else { throw new ClassCastException('\'' + key + "' doesn't map to a Vector object"); } } /** * Get a boolean associated with the given configuration key. * * @param key The configuration key. * @return The associated boolean. * @throws NoSuchElementException is thrown if the key doesn't * map to an existing object. * @throws ClassCastException is thrown if the key maps to an * object that is not a Boolean. */ public boolean getBoolean(String key) { Boolean b = getBoolean(key, null); if (b != null) { return b.booleanValue(); } else { throw new NoSuchElementException('\'' + key + "' doesn't map to an existing object"); } } /** * Get a boolean associated with the given configuration key. * * @param key The configuration key. * @param defaultValue The default value. * @return The associated boolean. * @throws ClassCastException is thrown if the key maps to an * object that is not a Boolean. */ public boolean getBoolean(String key, boolean defaultValue) { return getBoolean(key, new Boolean(defaultValue)).booleanValue(); } /** * Get a boolean associated with the given configuration key. * * @param key The configuration key. * @param defaultValue The default value. * @return The associated boolean if key is found and has valid * format, default value otherwise. * @throws ClassCastException is thrown if the key maps to an * object that is not a Boolean. */ public Boolean getBoolean(String key, Boolean defaultValue) { Object value = get(key); if (value instanceof Boolean) { return (Boolean) value; } else if (value instanceof String) { String s = testBoolean((String) value); Boolean b = new Boolean(s); put(key, b); return b; } else if (value == null) { if (defaults != null) { return defaults.getBoolean(key, defaultValue); } else { return defaultValue; } } else { throw new ClassCastException('\'' + key + "' doesn't map to a Boolean object"); } } /** * Test whether the string represent by value maps to a boolean * value or not. We will allow true, on, * and yes for a true boolean value, and * false, off, and no for * false boolean values. Case of value to test for * boolean status is ignored. * * @param value the value to test for boolean state * @return true or false if the supplied * text maps to a boolean value, or null otherwise. */ public String testBoolean(String value) { String s = value.toLowerCase(); if (s.equals("true") || s.equals("on") || s.equals("yes")) { return "true"; } else if (s.equals("false") || s.equals("off") || s.equals("no")) { return "false"; } else { return null; } } /** * Get a byte associated with the given configuration key. * * @param key The configuration key. * @return The associated byte. * @throws NoSuchElementException is thrown if the key doesn't * map to an existing object. * @throws ClassCastException is thrown if the key maps to an * object that is not a Byte. * @throws NumberFormatException is thrown if the value mapped * by the key has not a valid number format. */ public byte getByte(String key) { Byte b = getByte(key, null); if (b != null) { return b.byteValue(); } else { throw new NoSuchElementException('\'' + key + " doesn't map to an existing object"); } } /** * Get a byte associated with the given configuration key. * * @param key The configuration key. * @param defaultValue The default value. * @return The associated byte. * @throws ClassCastException is thrown if the key maps to an * object that is not a Byte. * @throws NumberFormatException is thrown if the value mapped * by the key has not a valid number format. */ public byte getByte(String key, byte defaultValue) { return getByte(key, new Byte(defaultValue)).byteValue(); } /** * Get a byte associated with the given configuration key. * * @param key The configuration key. * @param defaultValue The default value. * @return The associated byte if key is found and has valid * format, default value otherwise. * @throws ClassCastException is thrown if the key maps to an * object that is not a Byte. * @throws NumberFormatException is thrown if the value mapped * by the key has not a valid number format. */ public Byte getByte(String key, Byte defaultValue) { Object value = get(key); if (value instanceof Byte) { return (Byte) value; } else if (value instanceof String) { Byte b = new Byte((String) value); put(key, b); return b; } else if (value == null) { if (defaults != null) { return defaults.getByte(key, defaultValue); } else { return defaultValue; } } else { throw new ClassCastException('\'' + key + "' doesn't map to a Byte object"); } } /** * Get a short associated with the given configuration key. * * @param key The configuration key. * @return The associated short. * @throws NoSuchElementException is thrown if the key doesn't * map to an existing object. * @throws ClassCastException is thrown if the key maps to an * object that is not a Short. * @throws NumberFormatException is thrown if the value mapped * by the key has not a valid number format. */ public short getShort(String key) { Short s = getShort(key, null); if (s != null) { return s.shortValue(); } else { throw new NoSuchElementException('\'' + key + "' doesn't map to an existing object"); } } /** * Get a short associated with the given configuration key. * * @param key The configuration key. * @param defaultValue The default value. * @return The associated short. * @throws ClassCastException is thrown if the key maps to an * object that is not a Short. * @throws NumberFormatException is thrown if the value mapped * by the key has not a valid number format. */ public short getShort(String key, short defaultValue) { return getShort(key, new Short(defaultValue)).shortValue(); } /** * Get a short associated with the given configuration key. * * @param key The configuration key. * @param defaultValue The default value. * @return The associated short if key is found and has valid * format, default value otherwise. * @throws ClassCastException is thrown if the key maps to an * object that is not a Short. * @throws NumberFormatException is thrown if the value mapped * by the key has not a valid number format. */ public Short getShort(String key, Short defaultValue) { Object value = get(key); if (value instanceof Short) { return (Short) value; } else if (value instanceof String) { Short s = new Short((String) value); put(key, s); return s; } else if (value == null) { if (defaults != null) { return defaults.getShort(key, defaultValue); } else { return defaultValue; } } else { throw new ClassCastException('\'' + key + "' doesn't map to a Short object"); } } /** * The purpose of this method is to get the configuration resource * with the given name as an integer. * * @param name The resource name. * @return The value of the resource as an integer. */ public int getInt(String name) { return getInteger(name); } /** * The purpose of this method is to get the configuration resource * with the given name as an integer, or a default value. * * @param name The resource name * @param def The default value of the resource. * @return The value of the resource as an integer. */ public int getInt(String name, int def) { return getInteger(name, def); } /** * Get a int associated with the given configuration key. * * @param key The configuration key. * @return The associated int. * @throws NoSuchElementException is thrown if the key doesn't * map to an existing object. * @throws ClassCastException is thrown if the key maps to an * object that is not a Integer. * @throws NumberFormatException is thrown if the value mapped * by the key has not a valid number format. */ public int getInteger(String key) { Integer i = getInteger(key, null); if (i != null) { return i.intValue(); } else { throw new NoSuchElementException('\'' + key + "' doesn't map to an existing object"); } } /** * Get a int associated with the given configuration key. * * @param key The configuration key. * @param defaultValue The default value. * @return The associated int. * @throws ClassCastException is thrown if the key maps to an * object that is not a Integer. * @throws NumberFormatException is thrown if the value mapped * by the key has not a valid number format. */ public int getInteger(String key, int defaultValue) { Integer i = getInteger(key, null); if (i == null) { return defaultValue; } return i.intValue(); } /** * Get a int associated with the given configuration key. * * @param key The configuration key. * @param defaultValue The default value. * @return The associated int if key is found and has valid * format, default value otherwise. * @throws ClassCastException is thrown if the key maps to an * object that is not a Integer. * @throws NumberFormatException is thrown if the value mapped * by the key has not a valid number format. */ public Integer getInteger(String key, Integer defaultValue) { Object value = get(key); if (value instanceof Integer) { return (Integer) value; } else if (value instanceof String) { Integer i = new Integer((String) value); put(key, i); return i; } else if (value == null) { if (defaults != null) { return defaults.getInteger(key, defaultValue); } else { return defaultValue; } } else { throw new ClassCastException('\'' + key + "' doesn't map to a Integer object"); } } /** * Get a long associated with the given configuration key. * * @param key The configuration key. * @return The associated long. * @throws NoSuchElementException is thrown if the key doesn't * map to an existing object. * @throws ClassCastException is thrown if the key maps to an * object that is not a Long. * @throws NumberFormatException is thrown if the value mapped * by the key has not a valid number format. */ public long getLong(String key) { Long l = getLong(key, null); if (l != null) { return l.longValue(); } else { throw new NoSuchElementException('\'' + key + "' doesn't map to an existing object"); } } /** * Get a long associated with the given configuration key. * * @param key The configuration key. * @param defaultValue The default value. * @return The associated long. * @throws ClassCastException is thrown if the key maps to an * object that is not a Long. * @throws NumberFormatException is thrown if the value mapped * by the key has not a valid number format. */ public long getLong(String key, long defaultValue) { return getLong(key, new Long(defaultValue)).longValue(); } /** * Get a long associated with the given configuration key. * * @param key The configuration key. * @param defaultValue The default value. * @return The associated long if key is found and has valid * format, default value otherwise. * @throws ClassCastException is thrown if the key maps to an * object that is not a Long. * @throws NumberFormatException is thrown if the value mapped * by the key has not a valid number format. */ public Long getLong(String key, Long defaultValue) { Object value = get(key); if (value instanceof Long) { return (Long) value; } else if (value instanceof String) { Long l = new Long((String) value); put(key, l); return l; } else if (value == null) { if (defaults != null) { return defaults.getLong(key, defaultValue); } else { return defaultValue; } } else { throw new ClassCastException('\'' + key + "' doesn't map to a Long object"); } } /** * Get a float associated with the given configuration key. * * @param key The configuration key. * @return The associated float. * @throws NoSuchElementException is thrown if the key doesn't * map to an existing object. * @throws ClassCastException is thrown if the key maps to an * object that is not a Float. * @throws NumberFormatException is thrown if the value mapped * by the key has not a valid number format. */ public float getFloat(String key) { Float f = getFloat(key, null); if (f != null) { return f.floatValue(); } else { throw new NoSuchElementException('\'' + key + "' doesn't map to an existing object"); } } /** * Get a float associated with the given configuration key. * * @param key The configuration key. * @param defaultValue The default value. * @return The associated float. * @throws ClassCastException is thrown if the key maps to an * object that is not a Float. * @throws NumberFormatException is thrown if the value mapped * by the key has not a valid number format. */ public float getFloat(String key, float defaultValue) { return getFloat(key, new Float(defaultValue)).floatValue(); } /** * Get a float associated with the given configuration key. * * @param key The configuration key. * @param defaultValue The default value. * @return The associated float if key is found and has valid * format, default value otherwise. * @throws ClassCastException is thrown if the key maps to an * object that is not a Float. * @throws NumberFormatException is thrown if the value mapped * by the key has not a valid number format. */ public Float getFloat(String key, Float defaultValue) { Object value = get(key); if (value instanceof Float) { return (Float) value; } else if (value instanceof String) { Float f = new Float((String) value); put(key, f); return f; } else if (value == null) { if (defaults != null) { return defaults.getFloat(key, defaultValue); } else { return defaultValue; } } else { throw new ClassCastException('\'' + key + "' doesn't map to a Float object"); } } /** * Get a double associated with the given configuration key. * * @param key The configuration key. * @return The associated double. * @throws NoSuchElementException is thrown if the key doesn't * map to an existing object. * @throws ClassCastException is thrown if the key maps to an * object that is not a Double. * @throws NumberFormatException is thrown if the value mapped * by the key has not a valid number format. */ public double getDouble(String key) { Double d = getDouble(key, null); if (d != null) { return d.doubleValue(); } else { throw new NoSuchElementException('\'' + key + "' doesn't map to an existing object"); } } /** * Get a double associated with the given configuration key. * * @param key The configuration key. * @param defaultValue The default value. * @return The associated double. * @throws ClassCastException is thrown if the key maps to an * object that is not a Double. * @throws NumberFormatException is thrown if the value mapped * by the key has not a valid number format. */ public double getDouble(String key, double defaultValue) { return getDouble(key, new Double(defaultValue)).doubleValue(); } /** * Get a double associated with the given configuration key. * * @param key The configuration key. * @param defaultValue The default value. * @return The associated double if key is found and has valid * format, default value otherwise. * @throws ClassCastException is thrown if the key maps to an * object that is not a Double. * @throws NumberFormatException is thrown if the value mapped * by the key has not a valid number format. */ public Double getDouble(String key, Double defaultValue) { Object value = get(key); if (value instanceof Double) { return (Double) value; } else if (value instanceof String) { Double d = new Double((String) value); put(key, d); return d; } else if (value == null) { if (defaults != null) { return defaults.getDouble(key, defaultValue); } else { return defaultValue; } } else { throw new ClassCastException('\'' + key + "' doesn't map to a Double object"); } } /** * Convert a standard properties class into a configuration class. * * @param props the properties object to convert * @return new ExtendedProperties created from props */ public static ExtendedProperties convertProperties(Properties props) { ExtendedProperties c = new ExtendedProperties(); for (Enumeration e = props.keys(); e.hasMoreElements();) { String s = (String) e.nextElement(); c.setProperty(s, props.getProperty(s)); } return c; } } collections-generic-4.01/src/java/org/apache/commons/collections15/SortedBag.java0000644000175000017500000000305610464140760030176 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2002-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15; import java.util.Comparator; /** * Defines a type of Bag that maintains a sorted order among * its unique representative members. * * @author Matt Hall, John Watkinson, Chuck Burdick * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:19 $ * @since Commons Collections 2.0 */ public interface SortedBag extends Bag { /** * Returns the comparator associated with this sorted set, or null * if it uses its elements' natural ordering. * * @return the comparator in use, or null if natural ordering */ public Comparator comparator(); /** * Returns the first (lowest) member. * * @return the first element in the sorted bag */ public E first(); /** * Returns the last (highest) member. * * @return the last element in the sorted bag */ public E last(); } collections-generic-4.01/src/java/org/apache/commons/collections15/Predicate.java0000644000175000017500000000356710464140762030235 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15; /** * Defines a functor interface implemented by classes that perform a predicate * test on an object. *

* A Predicate is the object equivalent of an if statement. * It uses the input object to return a true or false value, and is often used in * validation or filtering. *

* Standard implementations of common predicates are provided by * {@link PredicateUtils}. These include true, false, instanceof, equals, and, * or, not, method invokation and null testing. * * @author James Strachan * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:19 $ * @since Commons Collections 1.0 */ public interface Predicate { /** * Use the specified parameter to perform a test that returns true or false. * * @param object the object to evaluate, should not be changed * @return true or false * @throws ClassCastException (runtime) if the input is the wrong class * @throws IllegalArgumentException (runtime) if the input is invalid * @throws FunctorException (runtime) if the predicate encounters a problem */ public boolean evaluate(T object); } collections-generic-4.01/src/java/org/apache/commons/collections15/buffer/0000755000175000017500000000000011664401370026726 5ustar giovannigiovannicollections-generic-4.01/src/java/org/apache/commons/collections15/buffer/BoundedFifoBuffer.java0000644000175000017500000002432010464140762033112 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2002-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.buffer; import org.apache.commons.collections15.BoundedCollection; import org.apache.commons.collections15.Buffer; import org.apache.commons.collections15.BufferOverflowException; import org.apache.commons.collections15.BufferUnderflowException; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.*; /** * The BoundedFifoBuffer is a very efficient implementation of * Buffer that does not alter the size of the buffer at runtime. *

* The removal order of a BoundedFifoBuffer is based on the * insertion order; elements are removed in the same order in which they * were added. The iteration order is the same as the removal order. *

* The {@link #add(Object)}, {@link #remove()} and {@link #get()} operations * all perform in constant time. All other operations perform in linear * time or worse. *

* Note that this implementation is not synchronized. The following can be * used to provide synchronized access to your BoundedFifoBuffer: *

 *   Buffer fifo = BufferUtils.synchronizedBuffer(new BoundedFifoBuffer());
 * 
*

* This buffer prevents null objects from being added. *

* This class is Serializable from Commons Collections 3.1. * * @author Avalon * @author Berin Loritsch * @author Paul Jack * @author Stephen Colebourne * @author Matt Hall, John Watkinson, Herve Quiroz * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:20 $ * @since Commons Collections 3.0 (previously in main package v2.1) */ public class BoundedFifoBuffer extends AbstractCollection implements Buffer, BoundedCollection, Serializable { /** * Serialization version */ private static final long serialVersionUID = 5603722811189451017L; private transient E[] elements; private transient int start = 0; private transient int end = 0; private transient boolean full = false; private final int maxElements; /** * Constructs a new BoundedFifoBuffer big enough to hold * 32 elements. */ public BoundedFifoBuffer() { this(32); } /** * Constructs a new BoundedFifoBuffer big enough to hold * the specified number of elements. * * @param size the maximum number of elements for this fifo * @throws IllegalArgumentException if the size is less than 1 */ public BoundedFifoBuffer(int size) { if (size <= 0) { throw new IllegalArgumentException("The size must be greater than 0"); } elements = (E[]) new Object[size]; maxElements = elements.length; } /** * Constructs a new BoundedFifoBuffer big enough to hold all * of the elements in the specified collection. That collection's * elements will also be added to the buffer. * * @param coll the collection whose elements to add, may not be null * @throws NullPointerException if the collection is null */ public BoundedFifoBuffer(Collection coll) { this(coll.size()); addAll(coll); } //----------------------------------------------------------------------- /** * Write the buffer out using a custom routine. * * @param out the output stream * @throws IOException */ private void writeObject(ObjectOutputStream out) throws IOException { out.defaultWriteObject(); out.writeInt(size()); for (Iterator it = iterator(); it.hasNext();) { out.writeObject(it.next()); } } /** * Read the buffer in using a custom routine. * * @param in the input stream * @throws IOException * @throws ClassNotFoundException */ private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); elements = (E[]) new Object[maxElements]; int size = in.readInt(); for (int i = 0; i < size; i++) { elements[i] = (E) in.readObject(); } start = 0; full = (size == maxElements); if (full) { end = 0; } else { end = size; } } //----------------------------------------------------------------------- /** * Returns the number of elements stored in the buffer. * * @return this buffer's size */ public int size() { int size = 0; if (end < start) { size = maxElements - start + end; } else if (end == start) { size = (full ? maxElements : 0); } else { size = end - start; } return size; } /** * Returns true if this buffer is empty; false otherwise. * * @return true if this buffer is empty */ public boolean isEmpty() { return size() == 0; } /** * Returns true if this collection is full and no new elements can be added. * * @return true if the collection is full */ public boolean isFull() { return size() == maxElements; } /** * Gets the maximum size of the collection (the bound). * * @return the maximum number of elements the collection can hold */ public int maxSize() { return maxElements; } /** * Clears this buffer. */ public void clear() { full = false; start = 0; end = 0; Arrays.fill(elements, null); } /** * Adds the given element to this buffer. * * @param element the element to add * @return true, always * @throws NullPointerException if the given element is null * @throws BufferOverflowException if this buffer is full */ public boolean add(E element) { if (null == element) { throw new NullPointerException("Attempted to add null object to buffer"); } if (full) { throw new BufferOverflowException("The buffer cannot hold more than " + maxElements + " objects."); } elements[end++] = element; if (end >= maxElements) { end = 0; } if (end == start) { full = true; } return true; } /** * Returns the least recently inserted element in this buffer. * * @return the least recently inserted element * @throws BufferUnderflowException if the buffer is empty */ public E get() { if (isEmpty()) { throw new BufferUnderflowException("The buffer is already empty"); } return elements[start]; } /** * Removes the least recently inserted element from this buffer. * * @return the least recently inserted element * @throws BufferUnderflowException if the buffer is empty */ public E remove() { if (isEmpty()) { throw new BufferUnderflowException("The buffer is already empty"); } E element = elements[start]; if (null != element) { elements[start++] = null; if (start >= maxElements) { start = 0; } full = false; } return element; } /** * Increments the internal index. * * @param index the index to increment * @return the updated index */ private int increment(int index) { index++; if (index >= maxElements) { index = 0; } return index; } /** * Decrements the internal index. * * @param index the index to decrement * @return the updated index */ private int decrement(int index) { index--; if (index < 0) { index = maxElements - 1; } return index; } /** * Returns an iterator over this buffer's elements. * * @return an iterator over this buffer's elements */ public Iterator iterator() { return new Iterator() { private int index = start; private int lastReturnedIndex = -1; private boolean isFirst = full; public boolean hasNext() { return isFirst || (index != end); } public E next() { if (!hasNext()) { throw new NoSuchElementException(); } isFirst = false; lastReturnedIndex = index; index = increment(index); return elements[lastReturnedIndex]; } public void remove() { if (lastReturnedIndex == -1) { throw new IllegalStateException(); } // First element can be removed quickly if (lastReturnedIndex == start) { BoundedFifoBuffer.this.remove(); lastReturnedIndex = -1; return; } // Other elements require us to shift the subsequent elements int i = lastReturnedIndex + 1; while (i != end) { if (i >= maxElements) { elements[i - 1] = elements[0]; i = 0; } else { elements[i - 1] = elements[i]; i++; } } lastReturnedIndex = -1; end = decrement(end); elements[end] = null; full = false; index = decrement(index); } }; } } collections-generic-4.01/src/java/org/apache/commons/collections15/buffer/UnboundedFifoBuffer.java0000644000175000017500000002240210464140754033455 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2002-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.buffer; import org.apache.commons.collections15.Buffer; import org.apache.commons.collections15.BufferUnderflowException; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.AbstractCollection; import java.util.Iterator; import java.util.NoSuchElementException; /** * UnboundedFifoBuffer is a very efficient buffer implementation. * According to performance testing, it exhibits a constant access time, but it * also outperforms ArrayList when used for the same purpose. *

* The removal order of an UnboundedFifoBuffer is based on the insertion * order; elements are removed in the same order in which they were added. * The iteration order is the same as the removal order. *

* The {@link #remove()} and {@link #get()} operations perform in constant time. * The {@link #add(Object)} operation performs in amortized constant time. All * other operations perform in linear time or worse. *

* Note that this implementation is not synchronized. The following can be * used to provide synchronized access to your UnboundedFifoBuffer: *

 *   Buffer fifo = BufferUtils.synchronizedBuffer(new UnboundedFifoBuffer());
 * 
*

* This buffer prevents null objects from being added. *

* This class is Serializable from Commons Collections 3.1. * * @author Avalon * @author Federico Barbieri * @author Berin Loritsch * @author Paul Jack * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:20 $ * @since Commons Collections 3.0 (previously in main package v2.1) */ public class UnboundedFifoBuffer extends AbstractCollection implements Buffer, Serializable { /** * Serialization vesrion */ private static final long serialVersionUID = -3482960336579541419L; /** * The array of objects in the buffer. */ protected transient E[] buffer; /** * The current head index. */ protected transient int head; /** * The current tail index. */ protected transient int tail; /** * Constructs an UnboundedFifoBuffer with the default number of elements. * It is exactly the same as performing the following: *

*

     *   new UnboundedFifoBuffer(32);
     * 
*/ public UnboundedFifoBuffer() { this(32); } /** * Constructs an UnboundedFifoBuffer with the specified number of elements. * The integer must be a positive integer. * * @param initialSize the initial size of the buffer * @throws IllegalArgumentException if the size is less than 1 */ public UnboundedFifoBuffer(int initialSize) { if (initialSize <= 0) { throw new IllegalArgumentException("The size must be greater than 0"); } buffer = (E[]) new Object[initialSize + 1]; head = 0; tail = 0; } //----------------------------------------------------------------------- /** * Write the buffer out using a custom routine. * * @param out the output stream * @throws IOException */ private void writeObject(ObjectOutputStream out) throws IOException { out.defaultWriteObject(); out.writeInt(size()); for (Iterator it = iterator(); it.hasNext();) { out.writeObject(it.next()); } } /** * Read the buffer in using a custom routine. * * @param in the input stream * @throws IOException * @throws ClassNotFoundException */ private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); int size = in.readInt(); buffer = (E[]) new Object[size]; for (int i = 0; i < size; i++) { buffer[i] = (E) in.readObject(); } head = 0; tail = size; } //----------------------------------------------------------------------- /** * Returns the number of elements stored in the buffer. * * @return this buffer's size */ public int size() { int size = 0; if (tail < head) { size = buffer.length - head + tail; } else { size = tail - head; } return size; } /** * Returns true if this buffer is empty; false otherwise. * * @return true if this buffer is empty */ public boolean isEmpty() { return (size() == 0); } /** * Adds the given element to this buffer. * * @param obj the element to add * @return true, always * @throws NullPointerException if the given element is null */ public boolean add(final E obj) { if (obj == null) { throw new NullPointerException("Attempted to add null object to buffer"); } if (size() + 1 >= buffer.length) { E[] tmp = (E[]) new Object[((buffer.length - 1) * 2) + 1]; int j = 0; for (int i = head; i != tail;) { tmp[j] = buffer[i]; buffer[i] = null; j++; i++; if (i == buffer.length) { i = 0; } } buffer = tmp; head = 0; tail = j; } buffer[tail] = obj; tail++; if (tail >= buffer.length) { tail = 0; } return true; } /** * Returns the next object in the buffer. * * @return the next object in the buffer * @throws BufferUnderflowException if this buffer is empty */ public E get() { if (isEmpty()) { throw new BufferUnderflowException("The buffer is already empty"); } return buffer[head]; } /** * Removes the next object from the buffer * * @return the removed object * @throws BufferUnderflowException if this buffer is empty */ public E remove() { if (isEmpty()) { throw new BufferUnderflowException("The buffer is already empty"); } E element = buffer[head]; if (null != element) { buffer[head] = null; head++; if (head >= buffer.length) { head = 0; } } return element; } /** * Increments the internal index. * * @param index the index to increment * @return the updated index */ private int increment(int index) { index++; if (index >= buffer.length) { index = 0; } return index; } /** * Decrements the internal index. * * @param index the index to decrement * @return the updated index */ private int decrement(int index) { index--; if (index < 0) { index = buffer.length - 1; } return index; } /** * Returns an iterator over this buffer's elements. * * @return an iterator over this buffer's elements */ public Iterator iterator() { return new Iterator() { private int index = head; private int lastReturnedIndex = -1; public boolean hasNext() { return index != tail; } public E next() { if (!hasNext()) { throw new NoSuchElementException(); } lastReturnedIndex = index; index = increment(index); return buffer[lastReturnedIndex]; } public void remove() { if (lastReturnedIndex == -1) { throw new IllegalStateException(); } // First element can be removed quickly if (lastReturnedIndex == head) { UnboundedFifoBuffer.this.remove(); lastReturnedIndex = -1; return; } // Other elements require us to shift the subsequent elements int i = lastReturnedIndex + 1; while (i != tail) { if (i >= buffer.length) { buffer[i - 1] = buffer[0]; i = 0; } else { buffer[i - 1] = buffer[i]; i++; } } lastReturnedIndex = -1; tail = decrement(tail); buffer[tail] = null; index = decrement(index); } }; } } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootcollections-generic-4.01/src/java/org/apache/commons/collections15/buffer/AbstractBufferDecorator.javacollections-generic-4.01/src/java/org/apache/commons/collections15/buffer/AbstractBufferDecorator.ja0000644000175000017500000000410710464140754034007 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.buffer; import org.apache.commons.collections15.Buffer; import org.apache.commons.collections15.collection.AbstractCollectionDecorator; /** * Decorates another Buffer to provide additional behaviour. *

* Methods are forwarded directly to the decorated buffer. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:20 $ * @since Commons Collections 3.0 */ public abstract class AbstractBufferDecorator extends AbstractCollectionDecorator implements Buffer { /** * Constructor only used in deserialization, do not use otherwise. * * @since Commons Collections 3.1 */ protected AbstractBufferDecorator() { super(); } /** * Constructor that wraps (not copies). * * @param buffer the buffer to decorate, must not be null * @throws IllegalArgumentException if list is null */ protected AbstractBufferDecorator(Buffer buffer) { super(buffer); } /** * Gets the buffer being decorated. * * @return the decorated buffer */ protected Buffer getBuffer() { return (Buffer) getCollection(); } //----------------------------------------------------------------------- public E get() { return getBuffer().get(); } public E remove() { return getBuffer().remove(); } } collections-generic-4.01/src/java/org/apache/commons/collections15/buffer/PriorityBuffer.java0000644000175000017500000004225710464140760032556 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.buffer; import org.apache.commons.collections15.Buffer; import org.apache.commons.collections15.BufferUnderflowException; import java.util.AbstractCollection; import java.util.Comparator; import java.util.Iterator; import java.util.NoSuchElementException; /** * Binary heap implementation of Buffer that provides for * removal based on Comparator ordering. *

* The removal order of a binary heap is based on either the natural sort * order of its elements or a specified {@link Comparator}. The * {@link #remove()} method always returns the first element as determined * by the sort order. (The ascendingOrder flag in the constructors * can be used to reverse the sort order, in which case {@link #remove()} * will always remove the last element.) The removal order is * not the same as the order of iteration; elements are * returned by the iterator in no particular order. *

* The {@link #add(Object)} and {@link #remove()} operations perform * in logarithmic time. The {@link #get()} operation performs in constant * time. All other operations perform in linear time or worse. *

* Note that this implementation is not synchronized. Use * {@link org.apache.commons.collections15.BufferUtils#synchronizedBuffer(Buffer)} or * {@link org.apache.commons.collections15.buffer.SynchronizedBuffer#decorate(Buffer)} * to provide synchronized access to a PriorityBuffer: *

*

 * Buffer heap = SynchronizedBuffer.decorate(new PriorityBuffer());
 * 
* * @author Peter Donald * @author Ram Chidambaram * @author Michael A. Smith * @author Paul Jack * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:20 $ * @since Commons Collections 3.0 (previously BinaryHeap v1.0) */ public class PriorityBuffer extends AbstractCollection implements Buffer { /** * The default capacity for the buffer. */ private static final int DEFAULT_CAPACITY = 13; /** * The elements in this buffer. */ protected E[] elements; /** * The number of elements currently in this buffer. */ protected int size; /** * If true, the first element as determined by the sort order will * be returned. If false, the last element as determined by the * sort order will be returned. */ protected boolean ascendingOrder; /** * The comparator used to order the elements */ protected Comparator comparator; //----------------------------------------------------------------------- /** * Constructs a new empty buffer that sorts in ascending order by the * natural order of the objects added. */ public PriorityBuffer() { this(DEFAULT_CAPACITY, true, null); } /** * Constructs a new empty buffer that sorts in ascending order using the * specified comparator. * * @param comparator the comparator used to order the elements, * null means use natural order */ public PriorityBuffer(Comparator comparator) { this(DEFAULT_CAPACITY, true, comparator); } /** * Constructs a new empty buffer specifying the sort order and using the * natural order of the objects added. * * @param ascendingOrder if true the heap is created as a * minimum heap; otherwise, the heap is created as a maximum heap */ public PriorityBuffer(boolean ascendingOrder) { this(DEFAULT_CAPACITY, ascendingOrder, null); } /** * Constructs a new empty buffer specifying the sort order and comparator. * * @param ascendingOrder true to use the order imposed by the given * comparator; false to reverse that order * @param comparator the comparator used to order the elements, * null means use natural order */ public PriorityBuffer(boolean ascendingOrder, Comparator comparator) { this(DEFAULT_CAPACITY, ascendingOrder, comparator); } /** * Constructs a new empty buffer that sorts in ascending order by the * natural order of the objects added, specifying an initial capacity. * * @param capacity the initial capacity for the buffer, greater than zero * @throws IllegalArgumentException if capacity is <= 0 */ public PriorityBuffer(int capacity) { this(capacity, true, null); } /** * Constructs a new empty buffer that sorts in ascending order using the * specified comparator and initial capacity. * * @param capacity the initial capacity for the buffer, greater than zero * @param comparator the comparator used to order the elements, * null means use natural order * @throws IllegalArgumentException if capacity is <= 0 */ public PriorityBuffer(int capacity, Comparator comparator) { this(capacity, true, comparator); } /** * Constructs a new empty buffer that specifying initial capacity and * sort order, using the natural order of the objects added. * * @param capacity the initial capacity for the buffer, greater than zero * @param ascendingOrder if true the heap is created as a * minimum heap; otherwise, the heap is created as a maximum heap. * @throws IllegalArgumentException if capacity is <= 0 */ public PriorityBuffer(int capacity, boolean ascendingOrder) { this(capacity, ascendingOrder, null); } /** * Constructs a new empty buffer that specifying initial capacity, * sort order and comparator. * * @param capacity the initial capacity for the buffer, greater than zero * @param ascendingOrder true to use the order imposed by the given * comparator; false to reverse that order * @param comparator the comparator used to order the elements, * null means use natural order * @throws IllegalArgumentException if capacity is <= 0 */ public PriorityBuffer(int capacity, boolean ascendingOrder, Comparator comparator) { super(); if (capacity <= 0) { throw new IllegalArgumentException("invalid capacity"); } this.ascendingOrder = ascendingOrder; //+1 as 0 is noop this.elements = (E[]) new Object[capacity + 1]; this.comparator = comparator; } //----------------------------------------------------------------------- /** * Checks whether the heap is ascending or descending order. * * @return true if ascending order (a min heap) */ public boolean isAscendingOrder() { return ascendingOrder; } /** * Gets the comparator being used for this buffer, null is natural order. * * @return the comparator in use, null is natural order */ public Comparator comparator() { return comparator; } //----------------------------------------------------------------------- /** * Returns the number of elements in this buffer. * * @return the number of elements in this buffer */ public int size() { return size; } /** * Clears all elements from the buffer. */ public void clear() { elements = (E[]) new Object[elements.length]; // for gc size = 0; } /** * Adds an element to the buffer. *

* The element added will be sorted according to the comparator in use. * * @param element the element to be added * @return true always */ public boolean add(E element) { if (isAtCapacity()) { grow(); } // percolate element to it's place in tree if (ascendingOrder) { percolateUpMinHeap(element); } else { percolateUpMaxHeap(element); } return true; } /** * Gets the next element to be removed without actually removing it (peek). * * @return the next element * @throws BufferUnderflowException if the buffer is empty */ public E get() { if (isEmpty()) { throw new BufferUnderflowException(); } else { return elements[1]; } } /** * Gets and removes the next element (pop). * * @return the next element * @throws BufferUnderflowException if the buffer is empty */ public E remove() { final E result = get(); elements[1] = elements[size--]; // set the unused element to 'null' so that the garbage collector // can free the object if not used anywhere else.(remove reference) elements[size + 1] = null; if (size != 0) { // percolate top element to it's place in tree if (ascendingOrder) { percolateDownMinHeap(1); } else { percolateDownMaxHeap(1); } } return result; } //----------------------------------------------------------------------- /** * Tests if the buffer is at capacity. * * @return true if buffer is full; false otherwise. */ protected boolean isAtCapacity() { //+1 as element 0 is noop return elements.length == size + 1; } /** * Percolates element down heap from the position given by the index. *

* Assumes it is a minimum heap. * * @param index the index for the element */ protected void percolateDownMinHeap(final int index) { final E element = elements[index]; int hole = index; while ((hole * 2) <= size) { int child = hole * 2; // if we have a right child and that child can not be percolated // up then move onto other child if (child != size && compare(elements[child + 1], elements[child]) < 0) { child++; } // if we found resting place of bubble then terminate search if (compare(elements[child], element) >= 0) { break; } elements[hole] = elements[child]; hole = child; } elements[hole] = element; } /** * Percolates element down heap from the position given by the index. *

* Assumes it is a maximum heap. * * @param index the index of the element */ protected void percolateDownMaxHeap(final int index) { final E element = elements[index]; int hole = index; while ((hole * 2) <= size) { int child = hole * 2; // if we have a right child and that child can not be percolated // up then move onto other child if (child != size && compare(elements[child + 1], elements[child]) > 0) { child++; } // if we found resting place of bubble then terminate search if (compare(elements[child], element) <= 0) { break; } elements[hole] = elements[child]; hole = child; } elements[hole] = element; } /** * Percolates element up heap from the position given by the index. *

* Assumes it is a minimum heap. * * @param index the index of the element to be percolated up */ protected void percolateUpMinHeap(final int index) { int hole = index; E element = elements[hole]; while (hole > 1 && compare(element, elements[hole / 2]) < 0) { // save element that is being pushed down // as the element "bubble" is percolated up final int next = hole / 2; elements[hole] = elements[next]; hole = next; } elements[hole] = element; } /** * Percolates a new element up heap from the bottom. *

* Assumes it is a minimum heap. * * @param element the element */ protected void percolateUpMinHeap(final E element) { elements[++size] = element; percolateUpMinHeap(size); } /** * Percolates element up heap from from the position given by the index. *

* Assume it is a maximum heap. * * @param index the index of the element to be percolated up */ protected void percolateUpMaxHeap(final int index) { int hole = index; E element = elements[hole]; while (hole > 1 && compare(element, elements[hole / 2]) > 0) { // save element that is being pushed down // as the element "bubble" is percolated up final int next = hole / 2; elements[hole] = elements[next]; hole = next; } elements[hole] = element; } /** * Percolates a new element up heap from the bottom. *

* Assume it is a maximum heap. * * @param element the element */ protected void percolateUpMaxHeap(final E element) { elements[++size] = element; percolateUpMaxHeap(size); } /** * Compares two objects using the comparator if specified, or the * natural order otherwise. * * @param a the first object * @param b the second object * @return -ve if a less than b, 0 if they are equal, +ve if a greater than b */ protected int compare(E a, E b) { if (comparator != null) { return comparator.compare(a, b); } else { return ((Comparable) a).compareTo(b); } } /** * Increases the size of the heap to support additional elements */ protected void grow() { final E[] array = (E[]) new Object[elements.length * 2]; System.arraycopy(elements, 0, array, 0, elements.length); elements = array; } //----------------------------------------------------------------------- /** * Returns an iterator over this heap's elements. * * @return an iterator over this heap's elements */ public Iterator iterator() { return new Iterator() { private int index = 1; private int lastReturnedIndex = -1; public boolean hasNext() { return index <= size; } public E next() { if (!hasNext()) { throw new NoSuchElementException(); } lastReturnedIndex = index; index++; return elements[lastReturnedIndex]; } public void remove() { if (lastReturnedIndex == -1) { throw new IllegalStateException(); } elements[lastReturnedIndex] = elements[size]; elements[size] = null; size--; if (size != 0 && lastReturnedIndex <= size) { int compareToParent = 0; if (lastReturnedIndex > 1) { compareToParent = compare(elements[lastReturnedIndex], elements[lastReturnedIndex / 2]); } if (ascendingOrder) { if (lastReturnedIndex > 1 && compareToParent < 0) { percolateUpMinHeap(lastReturnedIndex); } else { percolateDownMinHeap(lastReturnedIndex); } } else { // max heap if (lastReturnedIndex > 1 && compareToParent > 0) { percolateUpMaxHeap(lastReturnedIndex); } else { percolateDownMaxHeap(lastReturnedIndex); } } } index--; lastReturnedIndex = -1; } }; } /** * Returns a string representation of this heap. The returned string * is similar to those produced by standard JDK collections15. * * @return a string representation of this heap */ public String toString() { final StringBuffer sb = new StringBuffer(); sb.append("[ "); for (int i = 1; i < size + 1; i++) { if (i != 1) { sb.append(", "); } sb.append(elements[i]); } sb.append(" ]"); return sb.toString(); } } collections-generic-4.01/src/java/org/apache/commons/collections15/buffer/TransformedBuffer.java0000644000175000017500000000653110464140762033216 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.buffer; import org.apache.commons.collections15.Buffer; import org.apache.commons.collections15.Transformer; import org.apache.commons.collections15.collection.TransformedCollection; /** * Decorates another Buffer to transform objects that are added. *

* The add methods are affected by this class. * Thus objects must be removed or searched for using their transformed form. * For example, if the transformation converts Strings to Integers, you must * use the Integer form to remove objects. *

* This class is Serializable from Commons Collections 3.1. *

* Note: This class cannot support generics without breaking the Collection contract. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:20 $ * @since Commons Collections 3.0 */ public class TransformedBuffer extends TransformedCollection implements Buffer { /** * Serialization version */ private static final long serialVersionUID = -7901091318986132033L; /** * Factory method to create a transforming buffer. *

* If there are any elements already in the buffer being decorated, they * are NOT transformed. * * @param buffer the buffer to decorate, must not be null * @param transformer the transformer to use for conversion, must not be null * @return a new transformed Buffer * @throws IllegalArgumentException if buffer or transformer is null */ public static Buffer decorate(Buffer buffer, Transformer transformer) { return new TransformedBuffer(buffer, transformer); } //----------------------------------------------------------------------- /** * Constructor that wraps (not copies). *

* If there are any elements already in the buffer being decorated, they * are NOT transformed. * * @param buffer the buffer to decorate, must not be null * @param transformer the transformer to use for conversion, must not be null * @throws IllegalArgumentException if buffer or transformer is null */ protected TransformedBuffer(Buffer buffer, Transformer transformer) { super(buffer, transformer); } /** * Gets the decorated buffer. * * @return the decorated buffer */ protected Buffer getBuffer() { return (Buffer) collection; } //----------------------------------------------------------------------- public Object get() { return getBuffer().get(); } public Object remove() { return getBuffer().remove(); } } collections-generic-4.01/src/java/org/apache/commons/collections15/buffer/UnmodifiableBuffer.java0000644000175000017500000001011510464140754033322 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.buffer; import org.apache.commons.collections15.Buffer; import org.apache.commons.collections15.Unmodifiable; import org.apache.commons.collections15.iterators.UnmodifiableIterator; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.Collection; import java.util.Iterator; /** * Decorates another Buffer to ensure it can't be altered. *

* This class is Serializable from Commons Collections 3.1. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:20 $ * @since Commons Collections 3.0 */ public final class UnmodifiableBuffer extends AbstractBufferDecorator implements Unmodifiable, Serializable { /** * Serialization version */ private static final long serialVersionUID = 1832948656215393357L; /** * Factory method to create an unmodifiable buffer. *

* If the buffer passed in is already unmodifiable, it is returned. * * @param buffer the buffer to decorate, must not be null * @return an unmodifiable Buffer * @throws IllegalArgumentException if buffer is null */ public static Buffer decorate(Buffer buffer) { if (buffer instanceof Unmodifiable) { return buffer; } return new UnmodifiableBuffer(buffer); } //----------------------------------------------------------------------- /** * Constructor that wraps (not copies). * * @param buffer the buffer to decorate, must not be null * @throws IllegalArgumentException if buffer is null */ private UnmodifiableBuffer(Buffer buffer) { super(buffer); } //----------------------------------------------------------------------- /** * Write the collection out using a custom routine. * * @param out the output stream * @throws IOException */ private void writeObject(ObjectOutputStream out) throws IOException { out.defaultWriteObject(); out.writeObject(collection); } /** * Read the collection in using a custom routine. * * @param in the input stream * @throws IOException * @throws ClassNotFoundException */ private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); collection = (Collection) in.readObject(); } //----------------------------------------------------------------------- public Iterator iterator() { return UnmodifiableIterator.decorate(getCollection().iterator()); } public boolean add(E object) { throw new UnsupportedOperationException(); } public boolean addAll(Collection coll) { throw new UnsupportedOperationException(); } public void clear() { throw new UnsupportedOperationException(); } public boolean remove(Object object) { throw new UnsupportedOperationException(); } public boolean removeAll(Collection coll) { throw new UnsupportedOperationException(); } public boolean retainAll(Collection coll) { throw new UnsupportedOperationException(); } //----------------------------------------------------------------------- public E remove() { throw new UnsupportedOperationException(); } } collections-generic-4.01/src/java/org/apache/commons/collections15/buffer/CircularFifoBuffer.java0000644000175000017500000000613710464140754033305 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.buffer; import java.util.Collection; /** * CircularFifoBuffer is a first in first out buffer with a fixed size that * replaces its oldest element if full. *

* The removal order of a CircularFifoBuffer is based on the * insertion order; elements are removed in the same order in which they * were added. The iteration order is the same as the removal order. *

* The {@link #add(Object)}, {@link #remove()} and {@link #get()} operations * all perform in constant time. All other operations perform in linear * time or worse. *

* Note that this implementation is not synchronized. The following can be * used to provide synchronized access to your CircularFifoBuffer: *

 *   Buffer fifo = BufferUtils.synchronizedBuffer(new CircularFifoBuffer());
 * 
*

* This buffer prevents null objects from being added. *

* This class is Serializable from Commons Collections 3.1. * * @author Stefano Fornari * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:20 $ * @since Commons Collections 3.0 */ public class CircularFifoBuffer extends BoundedFifoBuffer { /** * Serialization version */ private static final long serialVersionUID = -8423413834657610406L; /** * Constructor that creates a buffer with the default size of 32. */ public CircularFifoBuffer() { super(32); } /** * Constructor that creates a buffer with the specified size. * * @param size the size of the buffer (cannot be changed) * @throws IllegalArgumentException if the size is less than 1 */ public CircularFifoBuffer(int size) { super(size); } /** * Constructor that creates a buffer from the specified collection. * The collection size also sets the buffer size * * @param coll the collection to copy into the buffer, may not be null * @throws NullPointerException if the collection is null */ public CircularFifoBuffer(Collection coll) { super(coll); } /** * If the buffer is full, the least recently added element is discarded so * that a new element can be inserted. * * @param element the element to add * @return true, always */ public boolean add(E element) { if (isFull()) { remove(); } return super.add(element); } } collections-generic-4.01/src/java/org/apache/commons/collections15/buffer/BlockingBuffer.java0000644000175000017500000000740510464140765032466 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.buffer; import org.apache.commons.collections15.Buffer; import org.apache.commons.collections15.BufferUnderflowException; import java.util.Collection; /** * Decorates another Buffer to make {@link #get()} and * {@link #remove()} block when the Buffer is empty. *

* If either get or remove is called on an empty * Buffer, the calling thread waits for notification that * an add or addAll operation has completed. *

* When one or more entries are added to an empty Buffer, * all threads blocked in get or remove are notified. * There is no guarantee that concurrent blocked get or * remove requests will be "unblocked" and receive data in the * order that they arrive. *

* This class is Serializable from Commons Collections 3.1. * * @author Stephen Colebourne * @author Janek Bogucki * @author Matt Hall, John Watkinson, Phil Steitz * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:20 $ * @since Commons Collections 3.0 */ public class BlockingBuffer extends SynchronizedBuffer { /** * Serialization version */ private static final long serialVersionUID = 1719328905017860541L; /** * Factory method to create a blocking buffer. * * @param buffer the buffer to decorate, must not be null * @return a new blocking Buffer * @throws IllegalArgumentException if buffer is null */ public static Buffer decorate(Buffer buffer) { return new BlockingBuffer(buffer); } //----------------------------------------------------------------------- /** * Constructor that wraps (not copies). * * @param buffer the buffer to decorate, must not be null * @throws IllegalArgumentException if the buffer is null */ protected BlockingBuffer(Buffer buffer) { super(buffer); } //----------------------------------------------------------------------- public boolean add(E o) { synchronized (lock) { boolean result = collection.add(o); notifyAll(); return result; } } public boolean addAll(Collection c) { synchronized (lock) { boolean result = collection.addAll(c); notifyAll(); return result; } } public E get() { synchronized (lock) { while (collection.isEmpty()) { try { wait(); } catch (InterruptedException e) { throw new BufferUnderflowException(); } } return getBuffer().get(); } } public E remove() { synchronized (lock) { while (collection.isEmpty()) { try { wait(); } catch (InterruptedException e) { throw new BufferUnderflowException(); } } return getBuffer().remove(); } } } collections-generic-4.01/src/java/org/apache/commons/collections15/buffer/PredicatedBuffer.java0000644000175000017500000000704510464140754033000 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.buffer; import org.apache.commons.collections15.Buffer; import org.apache.commons.collections15.Predicate; import org.apache.commons.collections15.collection.PredicatedCollection; /** * Decorates another Buffer to validate that additions * match a specified predicate. *

* This buffer exists to provide validation for the decorated buffer. * It is normally created to decorate an empty buffer. * If an object cannot be added to the buffer, an IllegalArgumentException is thrown. *

* One usage would be to ensure that no null entries are added to the buffer. *

Buffer buffer = PredicatedBuffer.decorate(new UnboundedFifoBuffer(), NotNullPredicate.INSTANCE);
*

* This class is Serializable from Commons Collections 3.1. * * @author Stephen Colebourne * @author Matt Hall, John Watkinson, Paul Jack * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:20 $ * @since Commons Collections 3.0 */ public class PredicatedBuffer extends PredicatedCollection implements Buffer { /** * Serialization version */ private static final long serialVersionUID = 2307609000539943581L; /** * Factory method to create a predicated (validating) buffer. *

* If there are any elements already in the buffer being decorated, they * are validated. * * @param buffer the buffer to decorate, must not be null * @param predicate the predicate to use for validation, must not be null * @return a new predicated Buffer * @throws IllegalArgumentException if buffer or predicate is null * @throws IllegalArgumentException if the buffer contains invalid elements */ public static Buffer decorate(Buffer buffer, Predicate predicate) { return new PredicatedBuffer(buffer, predicate); } //----------------------------------------------------------------------- /** * Constructor that wraps (not copies). *

* If there are any elements already in the collection being decorated, they * are validated. * * @param buffer the buffer to decorate, must not be null * @param predicate the predicate to use for validation, must not be null * @throws IllegalArgumentException if buffer or predicate is null * @throws IllegalArgumentException if the buffer contains invalid elements */ protected PredicatedBuffer(Buffer buffer, Predicate predicate) { super(buffer, predicate); } /** * Gets the buffer being decorated. * * @return the decorated buffer */ protected Buffer getBuffer() { return (Buffer) getCollection(); } //----------------------------------------------------------------------- public E get() { return getBuffer().get(); } public E remove() { return getBuffer().remove(); } } collections-generic-4.01/src/java/org/apache/commons/collections15/buffer/TypedBuffer.java0000644000175000017500000000411110464140754032010 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.buffer; import org.apache.commons.collections15.Buffer; import org.apache.commons.collections15.functors.InstanceofPredicate; /** * Decorates another Buffer to validate that elements added * are of a specific type. *

* The validation of additions is performed via an instanceof test against * a specified Class. If an object cannot be added to the * collection, an IllegalArgumentException is thrown. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @author Matthew Hawthorne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:20 $ * @since Commons Collections 3.0 */ public class TypedBuffer { /** * Factory method to create a typed list. *

* If there are any elements already in the buffer being decorated, they * are validated. * * @param buffer the buffer to decorate, must not be null * @param type the type to allow into the buffer, must not be null * @return a new typed Buffer * @throws IllegalArgumentException if buffer or type is null * @throws IllegalArgumentException if the buffer contains invalid elements */ public static Buffer decorate(Buffer buffer, Class type) { return new PredicatedBuffer(buffer, InstanceofPredicate.getInstance(type)); } /** * Restrictive constructor. */ protected TypedBuffer() { super(); } } collections-generic-4.01/src/java/org/apache/commons/collections15/buffer/package.html0000644000175000017500000000332210464140754031212 0ustar giovannigiovanni

This package contains implementations of the {@link org.apache.commons.collections.Buffer Buffer} interface.

The following implementations are provided in the package:

  • PriorityBuffer - provides for removal based on a comparator ordering
  • BoundedFifoBuffer - implements a buffer with a fixed size that throws exceptions when full
  • CircularFifoBuffer - implements a buffer with a fixed size that discards oldest when full
  • UnboundedFifoBuffer - implements a buffer that grows in size if necessary

The following decorators are provided in the package:

  • Synchronized - synchronizes method access for multi-threaded environments
  • Unmodifiable - ensures the collection cannot be altered
  • Predicated - ensures that only elements that are valid according to a predicate can be added
  • Typed - ensures that only elements that are of a specific type can be added
  • Transformed - transforms elements added to the buffer
  • Blocking - blocks on get and remove until an element is available
collections-generic-4.01/src/java/org/apache/commons/collections15/buffer/SynchronizedBuffer.java0000644000175000017500000000567110464140755033417 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.buffer; import org.apache.commons.collections15.Buffer; import org.apache.commons.collections15.collection.SynchronizedCollection; /** * Decorates another Buffer to synchronize its behaviour * for a multi-threaded environment. *

* Methods are synchronized, then forwarded to the decorated buffer. *

* This class is Serializable from Commons Collections 3.1. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:20 $ * @since Commons Collections 3.0 */ public class SynchronizedBuffer extends SynchronizedCollection implements Buffer { /** * Serialization version */ private static final long serialVersionUID = -6859936183953626253L; /** * Factory method to create a synchronized buffer. * * @param buffer the buffer to decorate, must not be null * @return a new synchronized Buffer * @throws IllegalArgumentException if buffer is null */ public static Buffer decorate(Buffer buffer) { return new SynchronizedBuffer(buffer); } //----------------------------------------------------------------------- /** * Constructor that wraps (not copies). * * @param buffer the buffer to decorate, must not be null * @throws IllegalArgumentException if the buffer is null */ protected SynchronizedBuffer(Buffer buffer) { super(buffer); } /** * Constructor that wraps (not copies). * * @param buffer the buffer to decorate, must not be null * @param lock the lock object to use, must not be null * @throws IllegalArgumentException if the buffer is null */ protected SynchronizedBuffer(Buffer buffer, Object lock) { super(buffer, lock); } /** * Gets the buffer being decorated. * * @return the decorated buffer */ protected Buffer getBuffer() { return (Buffer) collection; } //----------------------------------------------------------------------- public E get() { synchronized (lock) { return getBuffer().get(); } } public E remove() { synchronized (lock) { return getBuffer().remove(); } } } collections-generic-4.01/src/java/org/apache/commons/collections15/map/0000755000175000017500000000000011664401370026232 5ustar giovannigiovannicollections-generic-4.01/src/java/org/apache/commons/collections15/map/HashedMap.java0000644000175000017500000000660510464140762030740 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.map; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.Map; /** * A Map implementation that is a general purpose alternative * to HashMap. *

* This implementation improves on the JDK1.4 HashMap by adding the * {@link org.apache.commons.collections15.MapIterator MapIterator} * functionality and many methods for subclassing. *

* * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:32 $ * @since Commons Collections 3.0 */ public class HashedMap extends AbstractHashedMap implements Serializable, Cloneable { /** * Serialisation version */ private static final long serialVersionUID = -1788199231038721040L; /** * Constructs a new empty map with default size and load factor. */ public HashedMap() { super(DEFAULT_CAPACITY, DEFAULT_LOAD_FACTOR, DEFAULT_THRESHOLD); } /** * Constructs a new, empty map with the specified initial capacity. * * @param initialCapacity the initial capacity * @throws IllegalArgumentException if the initial capacity is less than one */ public HashedMap(int initialCapacity) { super(initialCapacity); } /** * Constructs a new, empty map with the specified initial capacity and * load factor. * * @param initialCapacity the initial capacity * @param loadFactor the load factor * @throws IllegalArgumentException if the initial capacity is less than one * @throws IllegalArgumentException if the load factor is less than zero */ public HashedMap(int initialCapacity, float loadFactor) { super(initialCapacity, loadFactor); } /** * Constructor copying elements from another map. * * @param map the map to copy * @throws NullPointerException if the map is null */ public HashedMap(Map map) { super(map); } //----------------------------------------------------------------------- /** * Clones the map without cloning the keys or values. * * @return a shallow clone */ public Object clone() { return super.clone(); } /** * Write the map out using a custom routine. */ private void writeObject(ObjectOutputStream out) throws IOException { out.defaultWriteObject(); doWriteObject(out); } /** * Read the map in using a custom routine. */ private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); doReadObject(in); } } collections-generic-4.01/src/java/org/apache/commons/collections15/map/PredicatedSortedMap.java0000644000175000017500000001034610464140757032772 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.map; import org.apache.commons.collections15.Predicate; import java.util.Comparator; import java.util.SortedMap; /** * Decorates another SortedMap to validate that additions * match a specified predicate. *

* This map exists to provide validation for the decorated map. * It is normally created to decorate an empty map. * If an object cannot be added to the map, an IllegalArgumentException is thrown. *

* One usage would be to ensure that no null keys are added to the map. *

SortedMap map = PredicatedSortedSet.decorate(new TreeMap(), NotNullPredicate.INSTANCE, null);
*

* This class is Serializable from Commons Collections 3.1. * * @author Stephen Colebourne * @author Matt Hall, John Watkinson, Paul Jack * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:32 $ * @since Commons Collections 3.0 */ public class PredicatedSortedMap extends PredicatedMap implements SortedMap { /** * Serialization version */ private static final long serialVersionUID = 3359846175935304332L; /** * Factory method to create a predicated (validating) sorted map. *

* If there are any elements already in the list being decorated, they * are validated. * * @param map the map to decorate, must not be null * @param keyPredicate the predicate to validate the keys, null means no check * @param valuePredicate the predicate to validate to values, null means no check * @throws IllegalArgumentException if the map is null */ public static SortedMap decorate(SortedMap map, Predicate keyPredicate, Predicate valuePredicate) { return new PredicatedSortedMap(map, keyPredicate, valuePredicate); } //----------------------------------------------------------------------- /** * Constructor that wraps (not copies). * * @param map the map to decorate, must not be null * @param keyPredicate the predicate to validate the keys, null means no check * @param valuePredicate the predicate to validate to values, null means no check * @throws IllegalArgumentException if the map is null */ protected PredicatedSortedMap(SortedMap map, Predicate keyPredicate, Predicate valuePredicate) { super(map, keyPredicate, valuePredicate); } //----------------------------------------------------------------------- /** * Gets the map being decorated. * * @return the decorated map */ protected SortedMap getSortedMap() { return (SortedMap) map; } //----------------------------------------------------------------------- public K firstKey() { return getSortedMap().firstKey(); } public K lastKey() { return getSortedMap().lastKey(); } public Comparator comparator() { return getSortedMap().comparator(); } public SortedMap subMap(K fromKey, K toKey) { SortedMap map = getSortedMap().subMap(fromKey, toKey); return new PredicatedSortedMap(map, keyPredicate, valuePredicate); } public SortedMap headMap(K toKey) { SortedMap map = getSortedMap().headMap(toKey); return new PredicatedSortedMap(map, keyPredicate, valuePredicate); } public SortedMap tailMap(K fromKey) { SortedMap map = getSortedMap().tailMap(fromKey); return new PredicatedSortedMap(map, keyPredicate, valuePredicate); } } collections-generic-4.01/src/java/org/apache/commons/collections15/map/ReferenceIdentityMap.java0000644000175000017500000002077710464140764033164 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.map; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.lang.ref.Reference; /** * A Map implementation that allows mappings to be * removed by the garbage collector and matches keys and values based * on == not equals(). *

*

* When you construct a ReferenceIdentityMap, you can specify what kind * of references are used to store the map's keys and values. * If non-hard references are used, then the garbage collector can remove * mappings if a key or value becomes unreachable, or if the JVM's memory is * running low. For information on how the different reference types behave, * see {@link Reference}. *

* Different types of references can be specified for keys and values. * The default constructor uses hard keys and soft values, providing a * memory-sensitive cache. *

* This map is similar to * {@link org.apache.commons.collections15.map.ReferenceMap ReferenceMap}. * It differs in that keys and values in this class are compared using ==. *

* This map will violate the detail of various Map and map view contracts. * As a general rule, don't compare this map to other maps. *

* This {@link java.util.Map} implementation does not allow null elements. * Attempting to add a null key or value to the map will raise a NullPointerException. *

* This implementation is not synchronized. * You can use {@link java.util.Collections#synchronizedMap} to * provide synchronized access to a ReferenceIdentityMap. * Remember that synchronization will not stop the garbage collecter removing entries. *

* All the available iterators can be reset back to the start by casting to * ResettableIterator and calling reset(). * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:32 $ * @see java.lang.ref.Reference * @since Commons Collections 3.0 (previously in main package v2.1) */ public class ReferenceIdentityMap extends AbstractReferenceMap implements Serializable { /** * Serialization version */ private static final long serialVersionUID = -1266190134568365852L; /** * Constructs a new ReferenceIdentityMap that will * use hard references to keys and soft references to values. */ public ReferenceIdentityMap() { super(HARD, SOFT, DEFAULT_CAPACITY, DEFAULT_LOAD_FACTOR, false); } /** * Constructs a new ReferenceIdentityMap that will * use the specified types of references. * * @param keyType the type of reference to use for keys; * must be {@link #HARD}, {@link #SOFT}, {@link #WEAK} * @param valueType the type of reference to use for values; * must be {@link #HARD}, {@link #SOFT}, {@link #WEAK} */ public ReferenceIdentityMap(int keyType, int valueType) { super(keyType, valueType, DEFAULT_CAPACITY, DEFAULT_LOAD_FACTOR, false); } /** * Constructs a new ReferenceIdentityMap that will * use the specified types of references. * * @param keyType the type of reference to use for keys; * must be {@link #HARD}, {@link #SOFT}, {@link #WEAK} * @param valueType the type of reference to use for values; * must be {@link #HARD}, {@link #SOFT}, {@link #WEAK} * @param purgeValues should the value be automatically purged when the * key is garbage collected */ public ReferenceIdentityMap(int keyType, int valueType, boolean purgeValues) { super(keyType, valueType, DEFAULT_CAPACITY, DEFAULT_LOAD_FACTOR, purgeValues); } /** * Constructs a new ReferenceIdentityMap with the * specified reference types, load factor and initial capacity. * * @param keyType the type of reference to use for keys; * must be {@link #HARD}, {@link #SOFT}, {@link #WEAK} * @param valueType the type of reference to use for values; * must be {@link #HARD}, {@link #SOFT}, {@link #WEAK} * @param capacity the initial capacity for the map * @param loadFactor the load factor for the map */ public ReferenceIdentityMap(int keyType, int valueType, int capacity, float loadFactor) { super(keyType, valueType, capacity, loadFactor, false); } /** * Constructs a new ReferenceIdentityMap with the * specified reference types, load factor and initial capacity. * * @param keyType the type of reference to use for keys; * must be {@link #HARD}, {@link #SOFT}, {@link #WEAK} * @param valueType the type of reference to use for values; * must be {@link #HARD}, {@link #SOFT}, {@link #WEAK} * @param capacity the initial capacity for the map * @param loadFactor the load factor for the map * @param purgeValues should the value be automatically purged when the * key is garbage collected */ public ReferenceIdentityMap(int keyType, int valueType, int capacity, float loadFactor, boolean purgeValues) { super(keyType, valueType, capacity, loadFactor, purgeValues); } //----------------------------------------------------------------------- /** * Gets the hash code for the key specified. *

* This implementation uses the identity hash code. * * @param key the key to get a hash code for * @return the hash code */ protected int hash(Object key) { return System.identityHashCode(key); } /** * Gets the hash code for a MapEntry. *

* This implementation uses the identity hash code. * * @param key the key to get a hash code for, may be null * @param value the value to get a hash code for, may be null * @return the hash code, as per the MapEntry specification */ protected int hashEntry(Object key, Object value) { return System.identityHashCode(key) ^ System.identityHashCode(value); } /** * Compares two keys for equals. *

* This implementation converts the key from the entry to a real reference * before comparison and uses ==. * * @param key1 the first key to compare passed in from outside * @param key2 the second key extracted from the entry via entry.key * @return true if equal by identity */ protected boolean isEqualKey(Object key1, Object key2) { // GenericsNote: I am disabled this line because of the new way that reference maps work, the getKey() method dereferences them for us. //key2 = (keyType > HARD ? ((Reference) key2).get() : key2); return (key1 == key2); } /** * Compares two values for equals. *

* This implementation uses ==. * * @param value1 the first value to compare passed in from outside * @param value2 the second value extracted from the entry via getValue() * @return true if equal by identity */ protected boolean isEqualValue(Object value1, Object value2) { return (value1 == value2); } //----------------------------------------------------------------------- /** * Write the map out using a custom routine. */ private void writeObject(ObjectOutputStream out) throws IOException { out.defaultWriteObject(); doWriteObject(out); } /** * Read the map in using a custom routine. */ private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); doReadObject(in); } } collections-generic-4.01/src/java/org/apache/commons/collections15/map/MultiKeyMap.java0000644000175000017500000004016310464140761031303 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.map; import org.apache.commons.collections15.IterableMap; import org.apache.commons.collections15.MapIterator; import org.apache.commons.collections15.keyvalue.MultiKey; import java.io.Serializable; import java.util.Collection; import java.util.Iterator; import java.util.Map; import java.util.Set; /** * A Map implementation that uses multiple keys to map the value. *

* This class is the most efficient way to uses multiple keys to map to a value. * The best way to use this class is via the additional map-style methods. * These provide get, containsKey, put and * remove for individual keys which operate without extra object creation. *

* The additional methods are the main interface of this map. * As such, you will not normally hold this map in a variable of type Map. *

* The normal map methods take in and return a {@link MultiKey}. * If you try to use put() with any other object type a * ClassCastException is thrown. If you try to use null as * the key in put() a NullPointerException is thrown. *

* This map is implemented as a decorator of a AbstractHashedMap which * enables extra behaviour to be added easily. *

    *
  • MultiKeyMap.decorate(new LinkedMap()) creates an ordered map. *
  • MultiKeyMap.decorate(new LRUMap()) creates an least recently used map. *
  • MultiKeyMap.decorate(new ReferenceMap()) creates a garbage collector sensitive map. *
* Note that IdentityMap and ReferenceIdentityMap are unsuitable * for use as the key comparison would work on the whole MultiKey, not the elements within. *

* As an example, consider a least recently used cache that uses a String airline code * and a Locale to lookup the airline's name: *

 * private MultiKeyMap cache = MultiKeyMap.decorate(new LRUMap(50));
 * 

* public String getAirlineName(String code, String locale) { * String name = (String) cache.get(code, locale); * if (name == null) { * name = getAirlineNameFromDB(code, locale); * cache.put(code, locale, name); * } * return name; * } *

* * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:32 $ * @since Commons Collections 3.1 */ public class MultiKeyMap implements IterableMap, V>, Serializable { /** * Serialisation version */ private static final long serialVersionUID = -1788199231038721040L; /** * The decorated map */ protected final AbstractHashedMap, V> map; //----------------------------------------------------------------------- /** * Decorates the specified map to add the MultiKeyMap API and fast query. * The map must not be null and must be empty. * * @param map the map to decorate, not null * @throws IllegalArgumentException if the map is null or not empty */ public static MultiKeyMap decorate(AbstractHashedMap, V> map) { if (map == null) { throw new IllegalArgumentException("Map must not be null"); } if (map.size() > 0) { throw new IllegalArgumentException("Map must be empty"); } return new MultiKeyMap(map); } //----------------------------------------------------------------------- /** * Constructs a new MultiKeyMap that decorates a HashedMap. */ public MultiKeyMap() { super(); map = new HashedMap, V>(); } /** * Constructor that decorates the specified map and is called from * {@link #decorate(AbstractHashedMap)}. * The map must not be null and should be empty or only contain valid keys. * This constructor performs no validation. * * @param map the map to decorate */ protected MultiKeyMap(AbstractHashedMap, V> map) { super(); this.map = map; } //----------------------------------------------------------------------- /** * Gets the value mapped to the specified multi-key. * * @param keys the keys * @return the mapped value, null if no match */ public V get(K... keys) { int hashCode = hash(keys); AbstractHashedMap.HashEntry, V> entry = map.data[map.hashIndex(hashCode, map.data.length)]; while (entry != null) { if (entry.hashCode == hashCode && isEqualKey(entry, keys)) { return entry.getValue(); } entry = entry.next; } return null; } /** * Checks whether the map contains the specified multi-key. * * @param keys the keys * @return true if the map contains the key */ public boolean containsKey(K... keys) { int hashCode = hash(keys); AbstractHashedMap.HashEntry, V> entry = map.data[map.hashIndex(hashCode, map.data.length)]; while (entry != null) { if (entry.hashCode == hashCode && isEqualKey(entry, keys)) { return true; } entry = entry.next; } return false; } /** * For backwards compatibility, makes a call to the new varargs {@link MultiKeyMap#putMultiKey} */ public V put(K key1, K key2, V value) { return putMultiKey(value, key1, key2); } /** * For backwards compatibility, makes a call to the new varargs {@link MultiKeyMap#putMultiKey} */ public V put(K key1, K key2, K key3, V value) { return putMultiKey(value, key1, key2, key3); } /** * For backwards compatibility, makes a call to the new varargs {@link MultiKeyMap#putMultiKey} */ public V put(K key1, K key2, K key3, K key4, V value) { return putMultiKey(value, key1, key2, key3, key4); } /** * For backwards compatibility, makes a call to the new varargs {@link MultiKeyMap#putMultiKey} */ public V put(K key1, K key2, K key3, K key4, K key5, V value) { return putMultiKey(value, key1, key2, key3, key4, key5); } /** * Stores the value against the specified multi-key. * * @param value the value to store * @param keys the keys * @return the value previously mapped to this combined key, null if none */ public V putMultiKey(V value, K... keys) { int hashCode = hash(keys); int index = map.hashIndex(hashCode, map.data.length); AbstractHashedMap.HashEntry, V> entry = map.data[index]; while (entry != null) { if (entry.hashCode == hashCode && isEqualKey(entry, keys)) { V oldValue = entry.getValue(); map.updateEntry(entry, value); return oldValue; } entry = entry.next; } map.addMapping(index, hashCode, new MultiKey(keys), value); return null; } /** * Removes the specified multi-key from this map. * * @param keys the keys * @return the value mapped to the removed key, null if key not in map */ public Object remove(K... keys) { int hashCode = hash(keys); int index = map.hashIndex(hashCode, map.data.length); AbstractHashedMap.HashEntry, V> entry = map.data[index]; AbstractHashedMap.HashEntry, V> previous = null; while (entry != null) { if (entry.hashCode == hashCode && isEqualKey(entry, keys)) { Object oldValue = entry.getValue(); map.removeMapping(entry, index, previous); return oldValue; } previous = entry; entry = entry.next; } return null; } /** * Gets the hash code for the specified multi-key. * * @param keys the keys * @return the hash code */ protected int hash(K... keys) { int h = 0; for (int i = 0; i < keys.length; i++) { K key = keys[i]; if (key != null) { h ^= key.hashCode(); } } h += ~(h << 9); h ^= (h >>> 14); h += (h << 4); h ^= (h >>> 10); return h; } /** * Is the key equal to the combined key. * * @param entry the entry to compare to * @param keys the keys * @return true if the key matches */ protected boolean isEqualKey(AbstractHashedMap.HashEntry, V> entry, K... keys) { MultiKey multi = (MultiKey) entry.getKey(); if (multi.size() != keys.length) { return false; } else { for (int i = 0; i < keys.length; i++) { K key = keys[i]; if ((key == null ? multi.getKey(i) != null : !key.equals(multi.getKey(i)))) { return false; } } } return true; } //----------------------------------------------------------------------- /** * Removes all mappings where the first key is that specified. *

* This method removes all the mappings where the MultiKey * has one or more keys, and the first matches that specified. * * @param key1 the first key * @return true if any elements were removed */ public boolean removeAll(Object key1) { boolean modified = false; MapIterator it = mapIterator(); while (it.hasNext()) { MultiKey multi = (MultiKey) it.next(); if (multi.size() >= 1 && (key1 == null ? multi.getKey(0) == null : key1.equals(multi.getKey(0)))) { it.remove(); modified = true; } } return modified; } /** * Removes all mappings where the first two keys are those specified. *

* This method removes all the mappings where the MultiKey * has two or more keys, and the first two match those specified. * * @param key1 the first key * @param key2 the second key * @return true if any elements were removed */ public boolean removeAll(Object key1, Object key2) { boolean modified = false; MapIterator it = mapIterator(); while (it.hasNext()) { MultiKey multi = (MultiKey) it.next(); if (multi.size() >= 2 && (key1 == null ? multi.getKey(0) == null : key1.equals(multi.getKey(0))) && (key2 == null ? multi.getKey(1) == null : key2.equals(multi.getKey(1)))) { it.remove(); modified = true; } } return modified; } /** * Removes all mappings where the first three keys are those specified. *

* This method removes all the mappings where the MultiKey * has three or more keys, and the first three match those specified. * * @param key1 the first key * @param key2 the second key * @param key3 the third key * @return true if any elements were removed */ public boolean removeAll(Object key1, Object key2, Object key3) { boolean modified = false; MapIterator it = mapIterator(); while (it.hasNext()) { MultiKey multi = (MultiKey) it.next(); if (multi.size() >= 3 && (key1 == null ? multi.getKey(0) == null : key1.equals(multi.getKey(0))) && (key2 == null ? multi.getKey(1) == null : key2.equals(multi.getKey(1))) && (key3 == null ? multi.getKey(2) == null : key3.equals(multi.getKey(2)))) { it.remove(); modified = true; } } return modified; } /** * Removes all mappings where the first four keys are those specified. *

* This method removes all the mappings where the MultiKey * has four or more keys, and the first four match those specified. * * @param key1 the first key * @param key2 the second key * @param key3 the third key * @param key4 the fourth key * @return true if any elements were removed */ public boolean removeAll(Object key1, Object key2, Object key3, Object key4) { boolean modified = false; MapIterator it = mapIterator(); while (it.hasNext()) { MultiKey multi = (MultiKey) it.next(); if (multi.size() >= 4 && (key1 == null ? multi.getKey(0) == null : key1.equals(multi.getKey(0))) && (key2 == null ? multi.getKey(1) == null : key2.equals(multi.getKey(1))) && (key3 == null ? multi.getKey(2) == null : key3.equals(multi.getKey(2))) && (key4 == null ? multi.getKey(3) == null : key4.equals(multi.getKey(3)))) { it.remove(); modified = true; } } return modified; } //----------------------------------------------------------------------- /** * Check to ensure that input keys are valid MultiKey objects. * * @param key the key to check */ protected void checkKey(Object key) { if (key == null) { throw new NullPointerException("Key must not be null"); } } /** * Clones the map without cloning the keys or values. * * @return a shallow clone */ public Object clone() { return new MultiKeyMap((AbstractHashedMap) map.clone()); } /** * Puts the key and value into the map, where the key must be a non-null * MultiKey object. * * @param key the non-null MultiKey object * @param value the value to store * @return the previous value for the key * @throws NullPointerException if the key is null * @throws ClassCastException if the key is not a MultiKey */ public V put(MultiKey key, V value) { checkKey(key); return map.put(key, value); } /** * Puts all the keys and values into this map. * Each key must be non-null and a MultiKey object. * * @param mapToCopy the map to copy in. * @throws NullPointerException if the mapToCopy or any key within is null * @throws ClassCastException if any key is not a MultiKey */ public void putAll(Map, ? extends V> mapToCopy) { for (Iterator it = mapToCopy.keySet().iterator(); it.hasNext();) { Object key = it.next(); checkKey(key); } map.putAll(mapToCopy); } //----------------------------------------------------------------------- public MapIterator mapIterator() { return map.mapIterator(); } public int size() { return map.size(); } public boolean isEmpty() { return map.isEmpty(); } public boolean containsKey(Object key) { return map.containsKey(key); } public boolean containsValue(Object value) { return map.containsValue(value); } public V get(Object key) { return map.get(key); } public V remove(Object key) { return map.remove(key); } public void clear() { map.clear(); } public Set keySet() { return map.keySet(); } public Collection values() { return map.values(); } public Set entrySet() { return map.entrySet(); } public boolean equals(Object obj) { if (obj == this) { return true; } return map.equals(obj); } public int hashCode() { return map.hashCode(); } public String toString() { return map.toString(); } } collections-generic-4.01/src/java/org/apache/commons/collections15/map/AbstractReferenceMap.java0000644000175000017500000010136510464140765033130 0ustar giovannigiovanni// Converted, with some major refactors required. Not as memory-efficient as before, could use additional refactoring. // Perhaps use four different types of HashEntry classes for max efficiency: // normal HashEntry for HARD,HARD // HardRefEntry for HARD,(SOFT|WEAK) // RefHardEntry for (SOFT|WEAK),HARD // RefRefEntry for (SOFT|WEAK),(SOFT|WEAK) /* * Copyright 2002-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.map; import org.apache.commons.collections15.MapIterator; import org.apache.commons.collections15.keyvalue.DefaultMapEntry; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.lang.ref.Reference; import java.lang.ref.ReferenceQueue; import java.lang.ref.SoftReference; import java.lang.ref.WeakReference; import java.util.*; /** * An abstract implementation of a hash-based map that allows the entries to * be removed by the garbage collector. *

* This class implements all the features necessary for a subclass reference * hash-based map. Key-value entries are stored in instances of the * ReferenceEntry class which can be overridden and replaced. * The iterators can similarly be replaced, without the need to replace the KeySet, * EntrySet and Values view classes. *

* Overridable methods are provided to change the default hashing behaviour, and * to change how entries are added to and removed from the map. Hopefully, all you * need for unusual subclasses is here. *

* When you construct an AbstractReferenceMap, you can specify what * kind of references are used to store the map's keys and values. * If non-hard references are used, then the garbage collector can remove * mappings if a key or value becomes unreachable, or if the JVM's memory is * running low. For information on how the different reference types behave, * see {@link Reference}. *

* Different types of references can be specified for keys and values. * The keys can be configured to be weak but the values hard, * in which case this class will behave like a * * WeakHashMap. However, you can also specify hard keys and * weak values, or any other combination. The default constructor uses * hard keys and soft values, providing a memory-sensitive cache. *

* This {@link Map} implementation does not allow null elements. * Attempting to add a null key or value to the map will raise a * NullPointerException. *

* All the available iterators can be reset back to the start by casting to * ResettableIterator and calling reset(). *

* This implementation is not synchronized. * You can use {@link java.util.Collections#synchronizedMap} to * provide synchronized access to a ReferenceMap. * * @author Paul Jack * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:32 $ * @see java.lang.ref.Reference * @since Commons Collections 3.1 (extracted from ReferenceMap in 3.0) */ public abstract class AbstractReferenceMap extends AbstractHashedMap { /** * Constant indicating that hard references should be used */ public static final int HARD = 0; /** * Constant indicating that soft references should be used */ public static final int SOFT = 1; /** * Constant indicating that weak references should be used */ public static final int WEAK = 2; /** * The reference type for keys. Must be HARD, SOFT, WEAK. * * @serial */ protected int keyType; /** * The reference type for values. Must be HARD, SOFT, WEAK. * * @serial */ protected int valueType; /** * Should the value be automatically purged when the associated key has been collected? */ protected boolean purgeValues; /** * ReferenceQueue used to eliminate stale mappings. * See purge. */ private transient ReferenceQueue queue; //----------------------------------------------------------------------- /** * Constructor used during deserialization. */ protected AbstractReferenceMap() { super(); } /** * Constructs a new empty map with the specified reference types, * load factor and initial capacity. * * @param keyType the type of reference to use for keys; * must be {@link #SOFT} or {@link #WEAK} * @param valueType the type of reference to use for values; * must be {@link #SOFT} or {@link #WEAK} * @param capacity the initial capacity for the map * @param loadFactor the load factor for the map * @param purgeValues should the value be automatically purged when the * key is garbage collected */ protected AbstractReferenceMap(int keyType, int valueType, int capacity, float loadFactor, boolean purgeValues) { super(capacity, loadFactor); verify("keyType", keyType); verify("valueType", valueType); this.keyType = keyType; this.valueType = valueType; this.purgeValues = purgeValues; } /** * Initialise this subclass during construction, cloning or deserialization. */ protected void init() { queue = new ReferenceQueue(); } //----------------------------------------------------------------------- /** * Checks the type int is a valid value. * * @param name the name for error messages * @param type the type value to check * @throws IllegalArgumentException if the value if invalid */ private static void verify(String name, int type) { if ((type < HARD) || (type > WEAK)) { throw new IllegalArgumentException(name + " must be HARD, SOFT, WEAK."); } } //----------------------------------------------------------------------- /** * Gets the size of the map. * * @return the size */ public int size() { purgeBeforeRead(); return super.size(); } /** * Checks whether the map is currently empty. * * @return true if the map is currently size zero */ public boolean isEmpty() { purgeBeforeRead(); return super.isEmpty(); } /** * Checks whether the map contains the specified key. * * @param key the key to search for * @return true if the map contains the key */ public boolean containsKey(Object key) { purgeBeforeRead(); Entry entry = getEntry(key); if (entry == null) { return false; } return (entry.getValue() != null); } /** * Checks whether the map contains the specified value. * * @param value the value to search for * @return true if the map contains the value */ public boolean containsValue(Object value) { purgeBeforeRead(); if (value == null) { return false; } return super.containsValue(value); } /** * Gets the value mapped to the key specified. * * @param key the key * @return the mapped value, null if no match */ public V get(Object key) { purgeBeforeRead(); Entry entry = getEntry(key); if (entry == null) { return null; } return entry.getValue(); } /** * Puts a key-value mapping into this map. * Neither the key nor the value may be null. * * @param key the key to add, must not be null * @param value the value to add, must not be null * @return the value previously mapped to this key, null if none * @throws NullPointerException if either the key or value is null */ public V put(K key, V value) { if (key == null) { throw new NullPointerException("null keys not allowed"); } if (value == null) { throw new NullPointerException("null values not allowed"); } purgeBeforeWrite(); return super.put(key, value); } /** * Removes the specified mapping from this map. * * @param key the mapping to remove * @return the value mapped to the removed key, null if key not in map */ public V remove(Object key) { if (key == null) { return null; } purgeBeforeWrite(); return super.remove(key); } /** * Clears this map. */ public void clear() { super.clear(); while (queue.poll() != null) { } // drain the queue } //----------------------------------------------------------------------- /** * Gets a MapIterator over the reference map. * The iterator only returns valid key/value pairs. * * @return a map iterator */ public MapIterator mapIterator() { return new ReferenceMapIterator(this); } /** * Returns a set view of this map's entries. * An iterator returned entry is valid until next() is called again. * The setValue() method on the toArray entries has no effect. * * @return a set view of this map's entries */ public Set> entrySet() { if (entrySet == null) { entrySet = new ReferenceEntrySet(this); } return entrySet; } /** * Returns a set view of this map's keys. * * @return a set view of this map's keys */ public Set keySet() { if (keySet == null) { keySet = new ReferenceKeySet(this); } return keySet; } /** * Returns a collection view of this map's values. * * @return a set view of this map's values */ public Collection values() { if (values == null) { values = new ReferenceValues(this); } return values; } //----------------------------------------------------------------------- /** * Purges stale mappings from this map before read operations. *

* This implementation calls {@link #purge()} to maintain a consistent state. */ protected void purgeBeforeRead() { purge(); } /** * Purges stale mappings from this map before write operations. *

* This implementation calls {@link #purge()} to maintain a consistent state. */ protected void purgeBeforeWrite() { purge(); } /** * Purges stale mappings from this map. *

* Note that this method is not synchronized! Special * care must be taken if, for instance, you want stale * mappings to be removed on a periodic basis by some * background thread. */ protected void purge() { Reference ref = queue.poll(); while (ref != null) { purge(ref); ref = queue.poll(); } } /** * Purges the specified reference. * * @param ref the reference to purge */ protected void purge(Reference ref) { // The hashCode of the reference is the hashCode of the // mapping key, even if the reference refers to the // mapping value... int hash = ref.hashCode(); int index = hashIndex(hash, data.length); HashEntry previous = null; HashEntry entry = data[index]; while (entry != null) { if (((ReferenceEntry) entry).purge(ref)) { if (previous == null) { data[index] = entry.next; } else { previous.next = entry.next; } this.size--; return; } previous = entry; entry = entry.next; } } //----------------------------------------------------------------------- /** * Gets the entry mapped to the key specified. * * @param key the key * @return the entry, null if no match */ protected HashEntry getEntry(Object key) { if (key == null) { return null; } else { return super.getEntry(key); } } /** * Gets the hash code for a MapEntry. * Subclasses can override this, for example to use the identityHashCode. * * @param key the key to get a hash code for, may be null * @param value the value to get a hash code for, may be null * @return the hash code, as per the MapEntry specification */ protected int hashEntry(Object key, Object value) { return (key == null ? 0 : key.hashCode()) ^ (value == null ? 0 : value.hashCode()); } /** * Compares two keys, in internal converted form, to see if they are equal. *

* This implementation converts the key from the entry to a real reference * before comparison. * * @param key1 the first key to compare passed in from outside * @param key2 the second key extracted from the entry via entry.key * @return true if equal */ protected boolean isEqualKey(Object key1, Object key2) { //if ((key1 == null) && (key2 != null) || (key1 != null) || (key2 == null)) { // return false; //} // GenericsNote: Conversion from reference handled by getKey() which replaced all .key references //key2 = (keyType > HARD ? ((Reference) key2).get() : key2); return (key1 == key2 || key1.equals(key2)); } /** * Creates a ReferenceEntry instead of a HashEntry. * * @param next the next entry in sequence * @param hashCode the hash code to use * @param key the key to store * @param value the value to store * @return the newly created entry */ public HashEntry createEntry(HashEntry next, int hashCode, K key, V value) { return new ReferenceEntry(this, (ReferenceEntry) next, hashCode, key, value); } /** * Creates an entry set iterator. * * @return the entrySet iterator */ protected Iterator> createEntrySetIterator() { return new ReferenceEntrySetIterator(this); } /** * Creates an key set iterator. * * @return the keySet iterator */ protected Iterator createKeySetIterator() { return new ReferenceKeySetIterator(this); } /** * Creates an values iterator. * * @return the values iterator */ protected Iterator createValuesIterator() { return new ReferenceValuesIterator(this); } //----------------------------------------------------------------------- /** * EntrySet implementation. */ static class ReferenceEntrySet extends EntrySet { protected ReferenceEntrySet(AbstractHashedMap parent) { super(parent); } public Object[] toArray() { return toArray(new Object[0]); } public T[] toArray(T[] arr) { // special implementation to handle disappearing entries ArrayList> list = new ArrayList>(); Iterator> iterator = iterator(); while (iterator.hasNext()) { Map.Entry e = iterator.next(); list.add(new DefaultMapEntry(e.getKey(), e.getValue())); } return list.toArray(arr); } } //----------------------------------------------------------------------- /** * KeySet implementation. */ static class ReferenceKeySet extends KeySet { protected ReferenceKeySet(AbstractHashedMap parent) { super(parent); } public Object[] toArray() { return toArray(new Object[0]); } public T[] toArray(T[] arr) { // special implementation to handle disappearing keys List list = new ArrayList(parent.size()); for (Iterator it = iterator(); it.hasNext();) { list.add(it.next()); } return list.toArray(arr); } } //----------------------------------------------------------------------- /** * Values implementation. */ static class ReferenceValues extends Values { protected ReferenceValues(AbstractHashedMap parent) { super(parent); } public Object[] toArray() { return toArray(new Object[0]); } public T[] toArray(T[] arr) { // special implementation to handle disappearing values List list = new ArrayList(parent.size()); for (Iterator it = iterator(); it.hasNext();) { list.add(it.next()); } return list.toArray(arr); } } //----------------------------------------------------------------------- /** * A MapEntry implementation for the map. *

* If getKey() or getValue() returns null, it means * the mapping is stale and should be removed. * * @since Commons Collections 3.1 */ protected static class ReferenceEntry extends HashEntry { /** * The parent map */ protected final AbstractReferenceMap parent; protected Reference refKey; protected Reference refValue; /** * Creates a new entry object for the ReferenceMap. * * @param parent the parent map * @param next the next entry in the hash bucket * @param hashCode the hash code of the key * @param key the key * @param value the value */ public ReferenceEntry(AbstractReferenceMap parent, ReferenceEntry next, int hashCode, K key, V value) { super(next, hashCode, null, null); this.parent = parent; if (parent.keyType != HARD) { refKey = toReference(parent.keyType, key, hashCode); } else { this.setKey(key); } if (parent.valueType != HARD) { refValue = toReference(parent.valueType, value, hashCode); // the key hashCode is passed in deliberately } else { this.setValue(value); } } /** * Gets the key from the entry. * This method dereferences weak and soft keys and thus may return null. * * @return the key, which may be null if it was garbage collected */ public K getKey() { return (parent.keyType > HARD) ? refKey.get() : super.getKey(); } /** * Gets the value from the entry. * This method dereferences weak and soft value and thus may return null. * * @return the value, which may be null if it was garbage collected */ public V getValue() { return (parent.valueType > HARD) ? refValue.get() : super.getValue(); } /** * Sets the value of the entry. * * @param obj the object to store * @return the previous value */ public V setValue(V obj) { V old = getValue(); if (parent.valueType > HARD) { refValue.clear(); refValue = toReference(parent.valueType, obj, hashCode); } else { super.setValue(obj); } return old; } /** * Compares this map entry to another. *

* This implementation uses isEqualKey and * isEqualValue on the main map for comparison. * * @param obj the other map entry to compare to * @return true if equal, false if not */ public boolean equals(Object obj) { if (obj == this) { return true; } if (obj instanceof Map.Entry == false) { return false; } Map.Entry entry = (Map.Entry) obj; Object entryKey = entry.getKey(); // convert to hard reference Object entryValue = entry.getValue(); // convert to hard reference if ((entryKey == null) || (entryValue == null)) { return false; } // compare using map methods, aiding identity subclass // note that key is direct access and value is via method return parent.isEqualKey(entryKey, getKey()) && parent.isEqualValue(entryValue, getValue()); } /** * Gets the hashcode of the entry using temporary hard references. *

* This implementation uses hashEntry on the main map. * * @return the hashcode of the entry */ public int hashCode() { return parent.hashEntry(getKey(), getValue()); } /** * Constructs a reference of the given type to the given referent. * The reference is registered with the queue for later purging. * * @param type HARD, SOFT or WEAK * @param referent the object to refer to * @param hash the hash code of the key of the mapping; * this number might be different from referent.hashCode() if * the referent represents a value and not a key */ protected Reference toReference(int type, T referent, int hash) { switch (type) { case SOFT: return new SoftRef(hash, referent, parent.queue); case WEAK: return new WeakRef(hash, referent, parent.queue); default: throw new Error("Attempt to create hard reference in ReferenceMap!"); } } /** * Purges the specified reference * * @param ref the reference to purge * @return true or false */ boolean purge(Reference ref) { boolean r = (parent.keyType > HARD) && (refKey == ref); r = r || ((parent.valueType > HARD) && (refValue == ref)); if (r) { if (parent.keyType > HARD) { refKey.clear(); } if (parent.valueType > HARD) { refValue.clear(); } else if (parent.purgeValues) { setValue(null); } } return r; } /** * Gets the next entry in the bucket. * * @return the next entry in the bucket */ protected ReferenceEntry next() { return (ReferenceEntry) next; } } //----------------------------------------------------------------------- /** * The EntrySet iterator. */ static class ReferenceIteratorBase { /** * The parent map */ final AbstractReferenceMap parent; // These fields keep track of where we are in the table. int index; ReferenceEntry entry; ReferenceEntry previous; // These Object fields provide hard references to the // current and next entry; this assures that if hasNext() // returns true, next() will actually return a valid element. K nextKey; V nextValue; K currentKey; V currentValue; int expectedModCount; public ReferenceIteratorBase(AbstractReferenceMap parent) { super(); this.parent = parent; index = (parent.size() != 0 ? parent.data.length : 0); // have to do this here! size() invocation above // may have altered the modCount. expectedModCount = parent.modCount; } public boolean hasNext() { checkMod(); while (nextNull()) { ReferenceEntry e = entry; int i = index; while ((e == null) && (i > 0)) { i--; e = (ReferenceEntry) parent.data[i]; } entry = e; index = i; if (e == null) { currentKey = null; currentValue = null; return false; } nextKey = e.getKey(); nextValue = e.getValue(); if (nextNull()) { entry = entry.next(); } } return true; } private void checkMod() { if (parent.modCount != expectedModCount) { throw new ConcurrentModificationException(); } } private boolean nextNull() { return (nextKey == null) || (nextValue == null); } protected ReferenceEntry nextEntry() { checkMod(); if (nextNull() && !hasNext()) { throw new NoSuchElementException(); } previous = entry; entry = entry.next(); currentKey = nextKey; currentValue = nextValue; nextKey = null; nextValue = null; return previous; } protected ReferenceEntry currentEntry() { checkMod(); return previous; } public ReferenceEntry superNext() { return nextEntry(); } public void remove() { checkMod(); if (previous == null) { throw new IllegalStateException(); } parent.remove(currentKey); previous = null; currentKey = null; currentValue = null; expectedModCount = parent.modCount; } } /** * The EntrySet iterator. */ static class ReferenceEntrySetIterator extends ReferenceIteratorBase implements Iterator> { public ReferenceEntrySetIterator(AbstractReferenceMap abstractReferenceMap) { super(abstractReferenceMap); } public ReferenceEntry next() { return superNext(); } } /** * The keySet iterator. */ static class ReferenceKeySetIterator extends ReferenceIteratorBase implements Iterator { ReferenceKeySetIterator(AbstractReferenceMap parent) { super(parent); } public K next() { return nextEntry().getKey(); } } /** * The values iterator. */ static class ReferenceValuesIterator extends ReferenceIteratorBase implements Iterator { ReferenceValuesIterator(AbstractReferenceMap parent) { super(parent); } public V next() { return nextEntry().getValue(); } } /** * The MapIterator implementation. */ static class ReferenceMapIterator extends ReferenceIteratorBase implements MapIterator { protected ReferenceMapIterator(AbstractReferenceMap parent) { super(parent); } public K next() { return nextEntry().getKey(); } public K getKey() { HashEntry current = currentEntry(); if (current == null) { throw new IllegalStateException(AbstractHashedMap.GETKEY_INVALID); } return current.getKey(); } public V getValue() { HashEntry current = currentEntry(); if (current == null) { throw new IllegalStateException(AbstractHashedMap.GETVALUE_INVALID); } return current.getValue(); } public V setValue(V value) { HashEntry current = currentEntry(); if (current == null) { throw new IllegalStateException(AbstractHashedMap.SETVALUE_INVALID); } return current.setValue(value); } } //----------------------------------------------------------------------- // These two classes store the hashCode of the key of // of the mapping, so that after they're dequeued a quick // lookup of the bucket in the table can occur. /** * A soft reference holder. */ static class SoftRef extends SoftReference { /** * the hashCode of the key (even if the reference points to a value) */ private int hash; public SoftRef(int hash, T r, ReferenceQueue q) { super(r, q); this.hash = hash; } public int hashCode() { return hash; } } /** * A weak reference holder. */ static class WeakRef extends WeakReference { /** * the hashCode of the key (even if the reference points to a value) */ private int hash; public WeakRef(int hash, T r, ReferenceQueue q) { super(r, q); this.hash = hash; } public int hashCode() { return hash; } } //----------------------------------------------------------------------- /** * Replaces the superclass method to store the state of this class. *

* Serialization is not one of the JDK's nicest topics. Normal serialization will * initialise the superclass before the subclass. Sometimes however, this isn't * what you want, as in this case the put() method on read can be * affected by subclass state. *

* The solution adopted here is to serialize the state data of this class in * this protected method. This method must be called by the * writeObject() of the first serializable subclass. *

* Subclasses may override if they have a specific field that must be present * on read before this implementation will work. Generally, the read determines * what must be serialized here, if anything. * * @param out the output stream */ protected void doWriteObject(ObjectOutputStream out) throws IOException { out.writeInt(keyType); out.writeInt(valueType); out.writeBoolean(purgeValues); out.writeFloat(loadFactor); out.writeInt(data.length); for (MapIterator it = mapIterator(); it.hasNext();) { out.writeObject(it.next()); out.writeObject(it.getValue()); } out.writeObject(null); // null terminate map // do not call super.doWriteObject() as code there doesn't work for reference map } /** * Replaces the superclassm method to read the state of this class. *

* Serialization is not one of the JDK's nicest topics. Normal serialization will * initialise the superclass before the subclass. Sometimes however, this isn't * what you want, as in this case the put() method on read can be * affected by subclass state. *

* The solution adopted here is to deserialize the state data of this class in * this protected method. This method must be called by the * readObject() of the first serializable subclass. *

* Subclasses may override if the subclass has a specific field that must be present * before put() or calculateThreshold() will work correctly. * * @param in the input stream */ protected void doReadObject(ObjectInputStream in) throws IOException, ClassNotFoundException { this.keyType = in.readInt(); this.valueType = in.readInt(); this.purgeValues = in.readBoolean(); this.loadFactor = in.readFloat(); int capacity = in.readInt(); init(); data = new HashEntry[capacity]; while (true) { K key = (K) in.readObject(); if (key == null) { break; } V value = (V) in.readObject(); put(key, value); } threshold = calculateThreshold(data.length, loadFactor); // do not call super.doReadObject() as code there doesn't work for reference map } } collections-generic-4.01/src/java/org/apache/commons/collections15/map/TypedMap.java0000644000175000017500000000435210464140764030630 0ustar giovannigiovanni// TODO: Not yet converted, deprecated (by me). /* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.map; import org.apache.commons.collections15.functors.InstanceofPredicate; import java.util.Map; /** * Decorates another Map to validate that elements added * are of a specific type. *

* The validation of additions is performed via an instanceof test against * a specified Class. If an object cannot be added to the * collection, an IllegalArgumentException is thrown. *

* The returned implementation is Serializable from Commons Collections 3.1. * * @author Stephen Colebourne * @author Matt Hall, John Watkinson, Matthew Hawthorne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:32 $ * @since Commons Collections 3.0 * @deprecated no longer needed with Java generics. */ public class TypedMap { /** * Factory method to create a typed map. *

* If there are any elements already in the map being decorated, they * are validated. * * @param map the map to decorate, must not be null * @param keyType the type to allow as keys, must not be null * @param valueType the type to allow as values, must not be null * @throws IllegalArgumentException if list or type is null * @throws IllegalArgumentException if the list contains invalid elements */ public static Map decorate(Map map, Class keyType, Class valueType) { return new PredicatedMap(map, InstanceofPredicate.getInstance(keyType), InstanceofPredicate.getInstance(valueType)); } /** * Restrictive constructor. */ protected TypedMap() { } } collections-generic-4.01/src/java/org/apache/commons/collections15/map/UnmodifiableSortedMap.java0000644000175000017500000001136410464140760033317 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.map; import org.apache.commons.collections15.Unmodifiable; import org.apache.commons.collections15.collection.UnmodifiableCollection; import org.apache.commons.collections15.set.UnmodifiableSet; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.*; /** * Decorates another SortedMap to ensure it can't be altered. *

* This class is Serializable from Commons Collections 3.1. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:32 $ * @since Commons Collections 3.0 */ public final class UnmodifiableSortedMap extends AbstractSortedMapDecorator implements Unmodifiable, Serializable { /** * Serialization version */ private static final long serialVersionUID = 5805344239827376360L; /** * Factory method to create an unmodifiable sorted map. * * @param map the map to decorate, must not be null * @throws IllegalArgumentException if map is null */ public static SortedMap decorate(SortedMap map) { if (map instanceof Unmodifiable) { return map; } return new UnmodifiableSortedMap(map); } //----------------------------------------------------------------------- /** * Constructor that wraps (not copies). * * @param map the map to decorate, must not be null * @throws IllegalArgumentException if map is null */ private UnmodifiableSortedMap(SortedMap map) { super(map); } //----------------------------------------------------------------------- /** * Write the map out using a custom routine. * * @param out the output stream * @throws IOException * @since Commons Collections 3.1 */ private void writeObject(ObjectOutputStream out) throws IOException { out.defaultWriteObject(); out.writeObject(map); } /** * Read the map in using a custom routine. * * @param in the input stream * @throws IOException * @throws ClassNotFoundException * @since Commons Collections 3.1 */ private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); map = (Map) in.readObject(); } //----------------------------------------------------------------------- public void clear() { throw new UnsupportedOperationException(); } public V put(K key, V value) { throw new UnsupportedOperationException(); } public void putAll(Map mapToCopy) { throw new UnsupportedOperationException(); } public V remove(Object key) { throw new UnsupportedOperationException(); } public Set> entrySet() { Set> set = super.entrySet(); return UnmodifiableEntrySet.decorate(set); } public Set keySet() { Set set = super.keySet(); return UnmodifiableSet.decorate(set); } public Collection values() { Collection coll = super.values(); return UnmodifiableCollection.decorate(coll); } //----------------------------------------------------------------------- public K firstKey() { return getSortedMap().firstKey(); } public K lastKey() { return getSortedMap().lastKey(); } public Comparator comparator() { return getSortedMap().comparator(); } public SortedMap subMap(K fromKey, K toKey) { SortedMap map = getSortedMap().subMap(fromKey, toKey); return new UnmodifiableSortedMap(map); } public SortedMap headMap(K toKey) { SortedMap map = getSortedMap().headMap(toKey); return new UnmodifiableSortedMap(map); } public SortedMap tailMap(K fromKey) { SortedMap map = getSortedMap().tailMap(fromKey); return new UnmodifiableSortedMap(map); } } collections-generic-4.01/src/java/org/apache/commons/collections15/map/Flat3Map.java0000644000175000017500000010516710464140764030522 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.map; import org.apache.commons.collections15.IterableMap; import org.apache.commons.collections15.MapIterator; import org.apache.commons.collections15.ResettableIterator; import org.apache.commons.collections15.iterators.EmptyIterator; import org.apache.commons.collections15.iterators.EmptyMapIterator; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.*; /** * A Map implementation that stores data in simple fields until * the size is greater than 3. *

* This map is designed for performance and can outstrip HashMap. * It also has good garbage collection characteristics. *

    *
  • Optimised for operation at size 3 or less. *
  • Still works well once size 3 exceeded. *
  • Gets at size 3 or less are about 0-10% faster than HashMap, *
  • Puts at size 3 or less are over 4 times faster than HashMap. *
  • Performance 5% slower than HashMap once size 3 exceeded once. *
* The design uses two distinct modes of operation - flat and delegate. * While the map is size 3 or less, operations map straight onto fields using * switch statements. Once size 4 is reached, the map switches to delegate mode * and only switches back when cleared. In delegate mode, all operations are * forwarded straight to a HashMap resulting in the 5% performance loss. *

* The performance gains on puts are due to not needing to create a Map Entry * object. This is a large saving not only in performance but in garbage collection. *

* Whilst in flat mode this map is also easy for the garbage collector to dispatch. * This is because it contains no complex objects or arrays which slow the progress. *

* Do not use Flat3Map if the size is likely to grow beyond 3. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:32 $ * @since Commons Collections 3.0 */ public class Flat3Map implements IterableMap, Serializable, Cloneable { /** * Serialization version */ private static final long serialVersionUID = -6701087419741928296L; /** * The size of the map, used while in flat mode */ private transient int size; /** * Hash, used while in flat mode */ private transient int hash1; /** * Hash, used while in flat mode */ private transient int hash2; /** * Hash, used while in flat mode */ private transient int hash3; /** * Key, used while in flat mode */ private transient K key1; /** * Key, used while in flat mode */ private transient K key2; /** * Key, used while in flat mode */ private transient K key3; /** * Value, used while in flat mode */ private transient V value1; /** * Value, used while in flat mode */ private transient V value2; /** * Value, used while in flat mode */ private transient V value3; /** * Map, used while in delegate mode */ private transient AbstractHashedMap delegateMap; /** * Constructor. */ public Flat3Map() { super(); } /** * Constructor copying elements from another map. * * @param map the map to copy * @throws NullPointerException if the map is null */ public Flat3Map(Map map) { super(); putAll(map); } //----------------------------------------------------------------------- /** * Gets the value mapped to the key specified. * * @param key the key * @return the mapped value, null if no match */ public V get(Object key) { if (delegateMap != null) { return delegateMap.get(key); } if (key == null) { switch (size) { // drop through case 3: if (key3 == null) return value3; case 2: if (key2 == null) return value2; case 1: if (key1 == null) return value1; } } else { if (size > 0) { int hashCode = key.hashCode(); switch (size) { // drop through case 3: if (hash3 == hashCode && key.equals(key3)) return value3; case 2: if (hash2 == hashCode && key.equals(key2)) return value2; case 1: if (hash1 == hashCode && key.equals(key1)) return value1; } } } return null; } /** * Gets the size of the map. * * @return the size */ public int size() { if (delegateMap != null) { return delegateMap.size(); } return size; } /** * Checks whether the map is currently empty. * * @return true if the map is currently size zero */ public boolean isEmpty() { return (size() == 0); } //----------------------------------------------------------------------- /** * Checks whether the map contains the specified key. * * @param key the key to search for * @return true if the map contains the key */ public boolean containsKey(Object key) { if (delegateMap != null) { return delegateMap.containsKey(key); } if (key == null) { switch (size) { // drop through case 3: if (key3 == null) return true; case 2: if (key2 == null) return true; case 1: if (key1 == null) return true; } } else { if (size > 0) { int hashCode = key.hashCode(); switch (size) { // drop through case 3: if (hash3 == hashCode && key.equals(key3)) return true; case 2: if (hash2 == hashCode && key.equals(key2)) return true; case 1: if (hash1 == hashCode && key.equals(key1)) return true; } } } return false; } /** * Checks whether the map contains the specified value. * * @param value the value to search for * @return true if the map contains the key */ public boolean containsValue(Object value) { if (delegateMap != null) { return delegateMap.containsValue(value); } if (value == null) { // drop through switch (size) { case 3: if (value3 == null) return true; case 2: if (value2 == null) return true; case 1: if (value1 == null) return true; } } else { switch (size) { // drop through case 3: if (value.equals(value3)) return true; case 2: if (value.equals(value2)) return true; case 1: if (value.equals(value1)) return true; } } return false; } //----------------------------------------------------------------------- /** * Puts a key-value mapping into this map. * * @param key the key to add * @param value the value to add * @return the value previously mapped to this key, null if none */ public V put(K key, V value) { if (delegateMap != null) { return delegateMap.put(key, value); } // change existing mapping if (key == null) { switch (size) { // drop through case 3: if (key3 == null) { V old = value3; value3 = value; return old; } case 2: if (key2 == null) { V old = value2; value2 = value; return old; } case 1: if (key1 == null) { V old = value1; value1 = value; return old; } } } else { if (size > 0) { int hashCode = key.hashCode(); switch (size) { // drop through case 3: if (hash3 == hashCode && key.equals(key3)) { V old = value3; value3 = value; return old; } case 2: if (hash2 == hashCode && key.equals(key2)) { V old = value2; value2 = value; return old; } case 1: if (hash1 == hashCode && key.equals(key1)) { V old = value1; value1 = value; return old; } } } } // add new mapping switch (size) { default: convertToMap(); delegateMap.put(key, value); return null; case 2: hash3 = (key == null ? 0 : key.hashCode()); key3 = key; value3 = value; break; case 1: hash2 = (key == null ? 0 : key.hashCode()); key2 = key; value2 = value; break; case 0: hash1 = (key == null ? 0 : key.hashCode()); key1 = key; value1 = value; break; } size++; return null; } /** * Puts all the values from the specified map into this map. * * @param map the map to add * @throws NullPointerException if the map is null */ public void putAll(Map map) { int size = map.size(); if (size == 0) { return; } if (delegateMap != null) { delegateMap.putAll(map); return; } if (size < 4) { for (Iterator it = map.entrySet().iterator(); it.hasNext();) { Map.Entry entry = (Map.Entry) it.next(); put(entry.getKey(), entry.getValue()); } } else { convertToMap(); delegateMap.putAll(map); } } /** * Converts the flat map data to a map. */ private void convertToMap() { delegateMap = createDelegateMap(); switch (size) { // drop through case 3: delegateMap.put(key3, value3); case 2: delegateMap.put(key2, value2); case 1: delegateMap.put(key1, value1); } size = 0; hash1 = hash2 = hash3 = 0; key1 = key2 = key3 = null; value1 = value2 = value3 = null; } /** * Create an instance of the map used for storage when in delegation mode. *

* This can be overridden by subclasses to provide a different map implementation. * Not every AbstractHashedMap is suitable, identity and reference based maps * would be poor choices. * * @return a new AbstractHashedMap or subclass * @since Commons Collections 3.1 */ protected AbstractHashedMap createDelegateMap() { return new HashedMap(); } /** * Removes the specified mapping from this map. * * @param key the mapping to remove * @return the value mapped to the removed key, null if key not in map */ public V remove(Object key) { if (delegateMap != null) { return delegateMap.remove(key); } if (size == 0) { return null; } if (key == null) { switch (size) { // drop through case 3: if (key3 == null) { V old = value3; hash3 = 0; key3 = null; value3 = null; size = 2; return old; } if (key2 == null) { V old = value3; hash2 = hash3; key2 = key3; value2 = value3; hash3 = 0; key3 = null; value3 = null; size = 2; return old; } if (key1 == null) { V old = value3; hash1 = hash3; key1 = key3; value1 = value3; hash3 = 0; key3 = null; value3 = null; size = 2; return old; } return null; case 2: if (key2 == null) { V old = value2; hash2 = 0; key2 = null; value2 = null; size = 1; return old; } if (key1 == null) { V old = value2; hash1 = hash2; key1 = key2; value1 = value2; hash2 = 0; key2 = null; value2 = null; size = 1; return old; } return null; case 1: if (key1 == null) { V old = value1; hash1 = 0; key1 = null; value1 = null; size = 0; return old; } } } else { if (size > 0) { int hashCode = key.hashCode(); switch (size) { // drop through case 3: if (hash3 == hashCode && key.equals(key3)) { V old = value3; hash3 = 0; key3 = null; value3 = null; size = 2; return old; } if (hash2 == hashCode && key.equals(key2)) { V old = value3; hash2 = hash3; key2 = key3; value2 = value3; hash3 = 0; key3 = null; value3 = null; size = 2; return old; } if (hash1 == hashCode && key.equals(key1)) { V old = value3; hash1 = hash3; key1 = key3; value1 = value3; hash3 = 0; key3 = null; value3 = null; size = 2; return old; } return null; case 2: if (hash2 == hashCode && key.equals(key2)) { V old = value2; hash2 = 0; key2 = null; value2 = null; size = 1; return old; } if (hash1 == hashCode && key.equals(key1)) { V old = value2; hash1 = hash2; key1 = key2; value1 = value2; hash2 = 0; key2 = null; value2 = null; size = 1; return old; } return null; case 1: if (hash1 == hashCode && key.equals(key1)) { V old = value1; hash1 = 0; key1 = null; value1 = null; size = 0; return old; } } } } return null; } /** * Clears the map, resetting the size to zero and nullifying references * to avoid garbage collection issues. */ public void clear() { if (delegateMap != null) { delegateMap.clear(); // should aid gc delegateMap = null; // switch back to flat mode } else { size = 0; hash1 = hash2 = hash3 = 0; key1 = key2 = key3 = null; value1 = value2 = value3 = null; } } //----------------------------------------------------------------------- /** * Gets an iterator over the map. * Changes made to the iterator affect this map. *

* A MapIterator returns the keys in the map. It also provides convenient * methods to get the key and value, and set the value. * It avoids the need to create an entrySet/keySet/values object. * It also avoids creating the Map Entry object. * * @return the map iterator */ public MapIterator mapIterator() { if (delegateMap != null) { return delegateMap.mapIterator(); } if (size == 0) { return EmptyMapIterator.INSTANCE; } return new FlatMapIterator(this); } /** * FlatMapIterator */ static class FlatMapIterator implements MapIterator, ResettableIterator { private final Flat3Map parent; private int nextIndex = 0; private boolean canRemove = false; FlatMapIterator(Flat3Map parent) { super(); this.parent = parent; } public boolean hasNext() { return (nextIndex < parent.size); } public K next() { if (hasNext() == false) { throw new NoSuchElementException(AbstractHashedMap.NO_NEXT_ENTRY); } canRemove = true; nextIndex++; return getKey(); } public void remove() { if (canRemove == false) { throw new IllegalStateException(AbstractHashedMap.REMOVE_INVALID); } parent.remove(getKey()); nextIndex--; canRemove = false; } public K getKey() { if (canRemove == false) { throw new IllegalStateException(AbstractHashedMap.GETKEY_INVALID); } switch (nextIndex) { case 3: return parent.key3; case 2: return parent.key2; case 1: return parent.key1; } throw new IllegalStateException("Invalid map index"); } public V getValue() { if (canRemove == false) { throw new IllegalStateException(AbstractHashedMap.GETVALUE_INVALID); } switch (nextIndex) { case 3: return parent.value3; case 2: return parent.value2; case 1: return parent.value1; } throw new IllegalStateException("Invalid map index"); } public V setValue(V value) { if (canRemove == false) { throw new IllegalStateException(AbstractHashedMap.SETVALUE_INVALID); } V old = getValue(); switch (nextIndex) { case 3: parent.value3 = value; case 2: parent.value2 = value; case 1: parent.value1 = value; } return old; } public void reset() { nextIndex = 0; canRemove = false; } public String toString() { if (canRemove) { return "Iterator[" + getKey() + "=" + getValue() + "]"; } else { return "Iterator[]"; } } } /** * Gets the entrySet view of the map. * Changes made to the view affect this map. * The Map Entry is not an independent object and changes as the * iterator progresses. * To simply iterate through the entries, use {@link #mapIterator()}. * * @return the entrySet view */ public Set> entrySet() { if (delegateMap != null) { return delegateMap.entrySet(); } return new EntrySet(this); } /** * EntrySet */ static class EntrySet extends AbstractSet> { private final Flat3Map parent; EntrySet(Flat3Map parent) { super(); this.parent = parent; } public int size() { return parent.size(); } public void clear() { parent.clear(); } public boolean remove(Object obj) { if (obj instanceof Map.Entry == false) { return false; } Map.Entry entry = (Map.Entry) obj; Object key = entry.getKey(); boolean result = parent.containsKey(key); parent.remove(key); return result; } public Iterator> iterator() { if (parent.delegateMap != null) { return parent.delegateMap.entrySet().iterator(); } if (parent.size() == 0) { return EmptyIterator.INSTANCE; } return new EntrySetIterator(parent); } } static class EntrySetIterator extends IteratorBase implements Iterator> { public EntrySetIterator(Flat3Map flat3Map) { super(flat3Map); } public Entry next() { return superNext(); //To change body of implemented methods use File | Settings | File Templates. } } /** * EntrySetIterator and MapEntry */ static class IteratorBase implements Map.Entry { private final Flat3Map parent; private int nextIndex = 0; private boolean canRemove = false; IteratorBase(Flat3Map parent) { super(); this.parent = parent; } public boolean hasNext() { return (nextIndex < parent.size); } public void remove() { if (canRemove == false) { throw new IllegalStateException(AbstractHashedMap.REMOVE_INVALID); } parent.remove(getKey()); nextIndex--; canRemove = false; } public K getKey() { if (canRemove == false) { throw new IllegalStateException(AbstractHashedMap.GETKEY_INVALID); } switch (nextIndex) { case 3: return parent.key3; case 2: return parent.key2; case 1: return parent.key1; } throw new IllegalStateException("Invalid map index"); } public Map.Entry superNext() { if (hasNext() == false) { throw new NoSuchElementException(AbstractHashedMap.NO_NEXT_ENTRY); } canRemove = true; nextIndex++; return this; } public V getValue() { if (canRemove == false) { throw new IllegalStateException(AbstractHashedMap.GETVALUE_INVALID); } switch (nextIndex) { case 3: return parent.value3; case 2: return parent.value2; case 1: return parent.value1; } throw new IllegalStateException("Invalid map index"); } public V setValue(V value) { if (canRemove == false) { throw new IllegalStateException(AbstractHashedMap.SETVALUE_INVALID); } V old = getValue(); switch (nextIndex) { case 3: parent.value3 = value; case 2: parent.value2 = value; case 1: parent.value1 = value; } return old; } public boolean equals(Object obj) { if (canRemove == false) { return false; } if (obj instanceof Map.Entry == false) { return false; } Map.Entry other = (Map.Entry) obj; Object key = getKey(); Object value = getValue(); return (key == null ? other.getKey() == null : key.equals(other.getKey())) && (value == null ? other.getValue() == null : value.equals(other.getValue())); } public int hashCode() { if (canRemove == false) { return 0; } Object key = getKey(); Object value = getValue(); return (key == null ? 0 : key.hashCode()) ^ (value == null ? 0 : value.hashCode()); } public String toString() { if (canRemove) { return getKey() + "=" + getValue(); } else { return ""; } } } /** * Gets the keySet view of the map. * Changes made to the view affect this map. * To simply iterate through the keys, use {@link #mapIterator()}. * * @return the keySet view */ public Set keySet() { if (delegateMap != null) { return delegateMap.keySet(); } return new KeySet(this); } /** * KeySet */ static class KeySet extends AbstractSet { private final Flat3Map parent; KeySet(Flat3Map parent) { super(); this.parent = parent; } public int size() { return parent.size(); } public void clear() { parent.clear(); } public boolean contains(Object key) { return parent.containsKey(key); } public boolean remove(Object key) { boolean result = parent.containsKey(key); parent.remove(key); return result; } public Iterator iterator() { if (parent.delegateMap != null) { return parent.delegateMap.keySet().iterator(); } if (parent.size() == 0) { return EmptyIterator.INSTANCE; } return new KeySetIterator(parent); } } /** * KeySetIterator */ static class KeySetIterator extends IteratorBase implements Iterator { KeySetIterator(Flat3Map parent) { super(parent); } public K next() { superNext(); return getKey(); } } /** * Gets the values view of the map. * Changes made to the view affect this map. * To simply iterate through the values, use {@link #mapIterator()}. * * @return the values view */ public Collection values() { if (delegateMap != null) { return delegateMap.values(); } return new Values(this); } /** * Values */ static class Values extends AbstractCollection { private final Flat3Map parent; Values(Flat3Map parent) { super(); this.parent = parent; } public int size() { return parent.size(); } public void clear() { parent.clear(); } public boolean contains(Object value) { return parent.containsValue(value); } public Iterator iterator() { if (parent.delegateMap != null) { return parent.delegateMap.values().iterator(); } if (parent.size() == 0) { return EmptyIterator.INSTANCE; } return new ValuesIterator(parent); } } /** * ValuesIterator */ static class ValuesIterator extends IteratorBase implements Iterator { ValuesIterator(Flat3Map parent) { super(parent); } public V next() { superNext(); return getValue(); } } //----------------------------------------------------------------------- /** * Write the map out using a custom routine. */ private void writeObject(ObjectOutputStream out) throws IOException { out.defaultWriteObject(); out.writeInt(size()); for (MapIterator it = mapIterator(); it.hasNext();) { out.writeObject(it.next()); // key out.writeObject(it.getValue()); // value } } /** * Read the map in using a custom routine. */ private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); int count = in.readInt(); if (count > 3) { delegateMap = createDelegateMap(); } for (int i = count; i > 0; i--) { put((K) in.readObject(), (V) in.readObject()); } } //----------------------------------------------------------------------- /** * Clones the map without cloning the keys or values. * * @return a shallow clone * @since Commons Collections 3.1 */ public Object clone() { try { Flat3Map cloned = (Flat3Map) super.clone(); if (cloned.delegateMap != null) { cloned.delegateMap = (HashedMap) cloned.delegateMap.clone(); } return cloned; } catch (CloneNotSupportedException ex) { throw new InternalError(); } } /** * Compares this map with another. * * @param obj the object to compare to * @return true if equal */ public boolean equals(Object obj) { if (obj == this) { return true; } if (delegateMap != null) { return delegateMap.equals(obj); } if (obj instanceof Map == false) { return false; } Map other = (Map) obj; if (size != other.size()) { return false; } if (size > 0) { Object otherValue = null; switch (size) { // drop through case 3: if (other.containsKey(key3) == false) { otherValue = other.get(key3); if (value3 == null ? otherValue != null : !value3.equals(otherValue)) { return false; } } case 2: if (other.containsKey(key2) == false) { otherValue = other.get(key2); if (value2 == null ? otherValue != null : !value2.equals(otherValue)) { return false; } } case 1: if (other.containsKey(key1) == false) { otherValue = other.get(key1); if (value1 == null ? otherValue != null : !value1.equals(otherValue)) { return false; } } } } return true; } /** * Gets the standard Map hashCode. * * @return the hash code defined in the Map interface */ public int hashCode() { if (delegateMap != null) { return delegateMap.hashCode(); } int total = 0; switch (size) { // drop through case 3: total += (hash3 ^ (value3 == null ? 0 : value3.hashCode())); case 2: total += (hash2 ^ (value2 == null ? 0 : value2.hashCode())); case 1: total += (hash1 ^ (value1 == null ? 0 : value1.hashCode())); } return total; } /** * Gets the map as a String. * * @return a string version of the map */ public String toString() { if (delegateMap != null) { return delegateMap.toString(); } if (size == 0) { return "{}"; } StringBuffer buf = new StringBuffer(128); buf.append('{'); switch (size) { // drop through case 3: buf.append(key3); buf.append('='); buf.append(value3); buf.append(','); case 2: buf.append(key2); buf.append('='); buf.append(value2); buf.append(','); case 1: buf.append(key1); buf.append('='); buf.append(value1); } buf.append('}'); return buf.toString(); } } collections-generic-4.01/src/java/org/apache/commons/collections15/map/LinkedMap.java0000644000175000017500000002112410464140762030743 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.map; import org.apache.commons.collections15.iterators.UnmodifiableIterator; import org.apache.commons.collections15.iterators.UnmodifiableListIterator; import org.apache.commons.collections15.list.UnmodifiableList; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.*; /** * A Map implementation that maintains the order of the entries. * In this implementation order is maintained by original insertion. *

* This implementation improves on the JDK1.4 LinkedHashMap by adding the * {@link org.apache.commons.collections15.MapIterator MapIterator} * functionality, additional convenience methods and allowing * bidirectional iteration. It also implements OrderedMap. * In addition, non-interface methods are provided to access the map by index. *

* The orderedMapIterator() method provides direct access to a * bidirectional iterator. The iterators from the other views can also be cast * to OrderedIterator if required. *

* All the available iterators can be reset back to the start by casting to * ResettableIterator and calling reset(). *

* The implementation is also designed to be subclassed, with lots of useful * methods exposed. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:32 $ * @since Commons Collections 3.0 */ public class LinkedMap extends AbstractLinkedMap implements Serializable, Cloneable { /** * Serialisation version */ private static final long serialVersionUID = 9077234323521161066L; /** * Constructs a new empty map with default size and load factor. */ public LinkedMap() { super(DEFAULT_CAPACITY, DEFAULT_LOAD_FACTOR, DEFAULT_THRESHOLD); } /** * Constructs a new, empty map with the specified initial capacity. * * @param initialCapacity the initial capacity * @throws IllegalArgumentException if the initial capacity is less than one */ public LinkedMap(int initialCapacity) { super(initialCapacity); } /** * Constructs a new, empty map with the specified initial capacity and * load factor. * * @param initialCapacity the initial capacity * @param loadFactor the load factor * @throws IllegalArgumentException if the initial capacity is less than one * @throws IllegalArgumentException if the load factor is less than zero */ public LinkedMap(int initialCapacity, float loadFactor) { super(initialCapacity, loadFactor); } /** * Constructor copying elements from another map. * * @param map the map to copy * @throws NullPointerException if the map is null */ public LinkedMap(Map map) { super(map); } //----------------------------------------------------------------------- /** * Clones the map without cloning the keys or values. * * @return a shallow clone */ public Object clone() { return super.clone(); } /** * Write the map out using a custom routine. */ private void writeObject(ObjectOutputStream out) throws IOException { out.defaultWriteObject(); doWriteObject(out); } /** * Read the map in using a custom routine. */ private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); doReadObject(in); } //----------------------------------------------------------------------- /** * Gets the key at the specified index. * * @param index the index to retrieve * @return the key at the specified index * @throws IndexOutOfBoundsException if the index is invalid */ public K get(int index) { return getEntry(index).getKey(); } /** * Gets the value at the specified index. * * @param index the index to retrieve * @return the key at the specified index * @throws IndexOutOfBoundsException if the index is invalid */ public V getValue(int index) { return getEntry(index).getValue(); } /** * Gets the index of the specified key. * * @param key the key to find the index of * @return the index, or -1 if not found */ public int indexOf(Object key) { int i = 0; for (LinkEntry entry = header.after; entry != header; entry = entry.after, i++) { if (isEqualKey(key, entry.getKey())) { return i; } } return -1; } /** * Removes the element at the specified index. * * @param index the index of the object to remove * @return the previous value corresponding the key, * or null if none existed * @throws IndexOutOfBoundsException if the index is invalid */ public V remove(int index) { return remove(get(index)); } /** * Gets an unmodifiable List view of the keys. *

* The returned list is unmodifiable because changes to the values of * the list (using {@link java.util.ListIterator#set(Object)}) will * effectively remove the value from the list and reinsert that value at * the end of the list, which is an unexpected side effect of changing the * value of a list. This occurs because changing the key, changes when the * mapping is added to the map and thus where it appears in the list. *

* An alternative to this method is to use {@link #keySet()}. * * @return The ordered list of keys. * @see #keySet() */ public List asList() { return new LinkedMapList(this); } /** * List view of map. */ static class LinkedMapList extends AbstractList { final LinkedMap parent; LinkedMapList(LinkedMap parent) { this.parent = parent; } public int size() { return parent.size(); } public K get(int index) { return parent.get(index); } public boolean contains(Object obj) { return parent.containsKey(obj); } public int indexOf(Object obj) { return parent.indexOf(obj); } public int lastIndexOf(Object obj) { return parent.indexOf(obj); } public boolean containsAll(Collection coll) { return parent.keySet().containsAll(coll); } public K remove(int index) { throw new UnsupportedOperationException(); } public boolean remove(Object obj) { throw new UnsupportedOperationException(); } public boolean removeAll(Collection coll) { throw new UnsupportedOperationException(); } public boolean retainAll(Collection coll) { throw new UnsupportedOperationException(); } public void clear() { throw new UnsupportedOperationException(); } public Object[] toArray() { return parent.keySet().toArray(); } public T[] toArray(T[] array) { return parent.keySet().toArray(array); } public Iterator iterator() { return UnmodifiableIterator.decorate(parent.keySet().iterator()); } public ListIterator listIterator() { return UnmodifiableListIterator.decorate(super.listIterator()); } public ListIterator listIterator(int fromIndex) { return UnmodifiableListIterator.decorate(super.listIterator(fromIndex)); } public List subList(int fromIndexInclusive, int toIndexExclusive) { return UnmodifiableList.decorate(super.subList(fromIndexInclusive, toIndexExclusive)); } } } collections-generic-4.01/src/java/org/apache/commons/collections15/map/AbstractHashedMap.java0000644000175000017500000012605010464140762032421 0ustar giovannigiovanni// GenericsNote: Converted -- However, null keys will now be represented in the internal structures, a big change. /* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.map; import org.apache.commons.collections15.IterableMap; import org.apache.commons.collections15.KeyValue; import org.apache.commons.collections15.MapIterator; import org.apache.commons.collections15.iterators.EmptyIterator; import org.apache.commons.collections15.iterators.EmptyMapIterator; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.*; /** * An abstract implementation of a hash-based map which provides numerous points for * subclasses to override. *

* This class implements all the features necessary for a subclass hash-based map. * Key-value entries are stored in instances of the HashEntry class, * which can be overridden and replaced. The iterators can similarly be replaced, * without the need to replace the KeySet, EntrySet and Values view classes. *

* Overridable methods are provided to change the default hashing behaviour, and * to change how entries are added to and removed from the map. Hopefully, all you * need for unusual subclasses is here. *

* NOTE: From Commons Collections 3.1 this class extends AbstractMap. * This is to provide backwards compatibility for ReferenceMap between v3.0 and v3.1. * This extends clause will be removed in v4.0. * * @author java util HashMap * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:32 $ * @since Commons Collections 3.0 */ public class AbstractHashedMap extends AbstractMap implements IterableMap { protected static final String NO_NEXT_ENTRY = "No next() entry in the iteration"; protected static final String NO_PREVIOUS_ENTRY = "No previous() entry in the iteration"; protected static final String REMOVE_INVALID = "remove() can only be called once after next()"; protected static final String GETKEY_INVALID = "getKey() can only be called after next() and before remove()"; protected static final String GETVALUE_INVALID = "getValue() can only be called after next() and before remove()"; protected static final String SETVALUE_INVALID = "setValue() can only be called after next() and before remove()"; /** * The default capacity to use */ protected static final int DEFAULT_CAPACITY = 16; /** * The default threshold to use */ protected static final int DEFAULT_THRESHOLD = 12; /** * The default load factor to use */ protected static final float DEFAULT_LOAD_FACTOR = 0.75f; /** * The maximum capacity allowed */ protected static final int MAXIMUM_CAPACITY = 1 << 30; /** * An object for masking null */ protected static final Object NULL = new Object(); /** * Load factor, normally 0.75 */ protected transient float loadFactor; /** * The size of the map */ protected transient int size; /** * Map entries */ protected transient HashEntry[] data; /** * Size at which to rehash */ protected transient int threshold; /** * Modification count for iterators */ protected transient int modCount; /** * Entry set */ protected transient EntrySet entrySet; /** * Key set */ protected transient KeySet keySet; /** * Values */ protected transient Values values; /** * Constructor only used in deserialization, do not use otherwise. */ protected AbstractHashedMap() { super(); } /** * Constructor which performs no validation on the passed in parameters. * * @param initialCapacity the initial capacity, must be a power of two * @param loadFactor the load factor, must be > 0.0f and generally < 1.0f * @param threshold the threshold, must be sensible */ protected AbstractHashedMap(int initialCapacity, float loadFactor, int threshold) { super(); this.loadFactor = loadFactor; this.data = new HashEntry[initialCapacity]; this.threshold = threshold; init(); } /** * Constructs a new, empty map with the specified initial capacity and * default load factor. * * @param initialCapacity the initial capacity * @throws IllegalArgumentException if the initial capacity is less than one */ protected AbstractHashedMap(int initialCapacity) { this(initialCapacity, DEFAULT_LOAD_FACTOR); } /** * Constructs a new, empty map with the specified initial capacity and * load factor. * * @param initialCapacity the initial capacity * @param loadFactor the load factor * @throws IllegalArgumentException if the initial capacity is less than one * @throws IllegalArgumentException if the load factor is less than or equal to zero */ protected AbstractHashedMap(int initialCapacity, float loadFactor) { super(); if (initialCapacity < 1) { throw new IllegalArgumentException("Initial capacity must be greater than 0"); } if (loadFactor <= 0.0f || Float.isNaN(loadFactor)) { throw new IllegalArgumentException("Load factor must be greater than 0"); } this.loadFactor = loadFactor; this.threshold = calculateThreshold(initialCapacity, loadFactor); initialCapacity = calculateNewCapacity(initialCapacity); this.data = new HashEntry[initialCapacity]; init(); } /** * Constructor copying elements from another map. * * @param map the map to copy * @throws NullPointerException if the map is null */ protected AbstractHashedMap(Map map) { this(Math.max(2 * map.size(), DEFAULT_CAPACITY), DEFAULT_LOAD_FACTOR); putAll(map); } /** * Initialise subclasses during construction, cloning or deserialization. */ protected void init() { } //----------------------------------------------------------------------- /** * Gets the value mapped to the key specified. * * @param key the key * @return the mapped value, null if no match */ public V get(Object key) { int hashCode = hash((key == null) ? NULL : key); HashEntry entry = data[hashIndex(hashCode, data.length)]; // no local for hash index while (entry != null) { if (entry.hashCode == hashCode && isEqualKey(key, entry.key)) { return entry.getValue(); } entry = entry.next; } return null; } /** * Gets the size of the map. * * @return the size */ public int size() { return size; } /** * Checks whether the map is currently empty. * * @return true if the map is currently size zero */ public boolean isEmpty() { return (size == 0); } //----------------------------------------------------------------------- /** * Checks whether the map contains the specified key. * * @param key the key to search for * @return true if the map contains the key */ public boolean containsKey(Object key) { int hashCode = hash((key == null) ? NULL : key); HashEntry entry = data[hashIndex(hashCode, data.length)]; // no local for hash index while (entry != null) { if (entry.hashCode == hashCode && isEqualKey(key, entry.getKey())) { return true; } entry = entry.next; } return false; } /** * Checks whether the map contains the specified value. * * @param value the value to search for * @return true if the map contains the value */ public boolean containsValue(Object value) { if (value == null) { for (int i = 0, isize = data.length; i < isize; i++) { HashEntry entry = data[i]; while (entry != null) { if (entry.getValue() == null) { return true; } entry = entry.next; } } } else { for (int i = 0, isize = data.length; i < isize; i++) { HashEntry entry = data[i]; while (entry != null) { if (isEqualValue(value, entry.getValue())) { return true; } entry = entry.next; } } } return false; } //----------------------------------------------------------------------- /** * Puts a key-value mapping into this map. * * @param key the key to add * @param value the value to add * @return the value previously mapped to this key, null if none */ public V put(K key, V value) { int hashCode = hash((key == null) ? NULL : key); int index = hashIndex(hashCode, data.length); HashEntry entry = data[index]; while (entry != null) { if (entry.hashCode == hashCode && isEqualKey(key, entry.getKey())) { V oldValue = entry.getValue(); updateEntry(entry, value); return oldValue; } entry = entry.next; } addMapping(index, hashCode, key, value); return null; } /** * Puts all the values from the specified map into this map. *

* This implementation iterates around the specified map and * uses {@link #put(Object, Object)}. * * @param map the map to add * @throws NullPointerException if the map is null */ public void putAll(Map map) { int mapSize = map.size(); if (mapSize == 0) { return; } int newSize = (int) ((size + mapSize) / loadFactor + 1); ensureCapacity(calculateNewCapacity(newSize)); // Have to cast here because of compiler inference problems. for (Iterator it = map.entrySet().iterator(); it.hasNext();) { Map.Entry entry = (Map.Entry) it.next(); put(entry.getKey(), entry.getValue()); } } /** * Removes the specified mapping from this map. * * @param key the mapping to remove * @return the value mapped to the removed key, null if key not in map */ public V remove(Object key) { int hashCode = hash((key == null) ? NULL : key); int index = hashIndex(hashCode, data.length); HashEntry entry = data[index]; HashEntry previous = null; while (entry != null) { if (entry.hashCode == hashCode && isEqualKey(key, entry.getKey())) { V oldValue = entry.getValue(); removeMapping(entry, index, previous); return oldValue; } previous = entry; entry = entry.next; } return null; } /** * Clears the map, resetting the size to zero and nullifying references * to avoid garbage collection issues. */ public void clear() { modCount++; HashEntry[] data = this.data; for (int i = data.length - 1; i >= 0; i--) { data[i] = null; } size = 0; } /** * Gets the hash code for the key specified. * This implementation uses the additional hashing routine from JDK1.4. * Subclasses can override this to return alternate hash codes. * * @param key the key to get a hash code for * @return the hash code */ protected int hash(Object key) { // same as JDK 1.4 int h = key.hashCode(); h += ~(h << 9); h ^= (h >>> 14); h += (h << 4); h ^= (h >>> 10); return h; } /** * Compares two keys, in internal converted form, to see if they are equal. * This implementation uses the equals method. * Subclasses can override this to match differently. * * @param key1 the first key to compare passed in from outside * @param key2 the second key extracted from the entry via entry.key * @return true if equal */ protected boolean isEqualKey(Object key1, Object key2) { return (key1 == key2 || ((key1 != null) && key1.equals(key2))); } /** * Compares two values, in external form, to see if they are equal. * This implementation uses the equals method and assumes neither value is null. * Subclasses can override this to match differently. * * @param value1 the first value to compare passed in from outside * @param value2 the second value extracted from the entry via getValue() * @return true if equal */ protected boolean isEqualValue(Object value1, Object value2) { return (value1 == value2 || value1.equals(value2)); } /** * Gets the index into the data storage for the hashCode specified. * This implementation uses the least significant bits of the hashCode. * Subclasses can override this to return alternate bucketing. * * @param hashCode the hash code to use * @param dataSize the size of the data to pick a bucket from * @return the bucket index */ protected int hashIndex(int hashCode, int dataSize) { return hashCode & (dataSize - 1); } //----------------------------------------------------------------------- /** * Gets the entry mapped to the key specified. *

* This method exists for subclasses that may need to perform a multi-step * process accessing the entry. The public methods in this class don't use this * method to gain a small performance boost. * * @param key the key * @return the entry, null if no match */ protected HashEntry getEntry(Object key) { int hashCode = hash((key == null) ? NULL : key); HashEntry entry = data[hashIndex(hashCode, data.length)]; // no local for hash index while (entry != null) { if (entry.hashCode == hashCode && isEqualKey(key, entry.getKey())) { return entry; } entry = entry.next; } return null; } //----------------------------------------------------------------------- /** * Updates an existing key-value mapping to change the value. *

* This implementation calls setValue() on the entry. * Subclasses could override to handle changes to the map. * * @param entry the entry to update * @param newValue the new value to store */ protected void updateEntry(HashEntry entry, V newValue) { entry.setValue(newValue); } /** * Reuses an existing key-value mapping, storing completely new data. *

* This implementation sets all the data fields on the entry. * Subclasses could populate additional entry fields. * * @param entry the entry to update, not null * @param hashIndex the index in the data array * @param hashCode the hash code of the key to add * @param key the key to add * @param value the value to add */ protected void reuseEntry(HashEntry entry, int hashIndex, int hashCode, K key, V value) { entry.next = data[hashIndex]; entry.hashCode = hashCode; entry.key = key; entry.value = value; } //----------------------------------------------------------------------- /** * Adds a new key-value mapping into this map. *

* This implementation calls createEntry(), addEntry() * and checkCapacity(). * It also handles changes to modCount and size. * Subclasses could override to fully control adds to the map. * * @param hashIndex the index into the data array to store at * @param hashCode the hash code of the key to add * @param key the key to add * @param value the value to add */ protected void addMapping(int hashIndex, int hashCode, K key, V value) { modCount++; HashEntry entry = createEntry(data[hashIndex], hashCode, key, value); addEntry(entry, hashIndex); size++; checkCapacity(); } /** * Creates an entry to store the key-value data. *

* This implementation creates a new HashEntry instance. * Subclasses can override this to return a different storage class, * or implement caching. * * @param next the next entry in sequence * @param hashCode the hash code to use * @param key the key to store * @param value the value to store * @return the newly created entry */ protected HashEntry createEntry(HashEntry next, int hashCode, K key, V value) { return new HashEntry(next, hashCode, key, value); } /** * Adds an entry into this map. *

* This implementation adds the entry to the data storage table. * Subclasses could override to handle changes to the map. * * @param entry the entry to add * @param hashIndex the index into the data array to store at */ protected void addEntry(HashEntry entry, int hashIndex) { data[hashIndex] = entry; } //----------------------------------------------------------------------- /** * Removes a mapping from the map. *

* This implementation calls removeEntry() and destroyEntry(). * It also handles changes to modCount and size. * Subclasses could override to fully control removals from the map. * * @param entry the entry to remove * @param hashIndex the index into the data structure * @param previous the previous entry in the chain */ protected void removeMapping(HashEntry entry, int hashIndex, HashEntry previous) { modCount++; removeEntry(entry, hashIndex, previous); size--; destroyEntry(entry); } /** * Removes an entry from the chain stored in a particular index. *

* This implementation removes the entry from the data storage table. * The size is not updated. * Subclasses could override to handle changes to the map. * * @param entry the entry to remove * @param hashIndex the index into the data structure * @param previous the previous entry in the chain */ protected void removeEntry(HashEntry entry, int hashIndex, HashEntry previous) { if (previous == null) { data[hashIndex] = entry.next; } else { previous.next = entry.next; } } /** * Kills an entry ready for the garbage collector. *

* This implementation prepares the HashEntry for garbage collection. * Subclasses can override this to implement caching (override clear as well). * * @param entry the entry to destroy */ protected void destroyEntry(HashEntry entry) { entry.next = null; entry.key = null; entry.value = null; } //----------------------------------------------------------------------- /** * Checks the capacity of the map and enlarges it if necessary. *

* This implementation uses the threshold to check if the map needs enlarging */ protected void checkCapacity() { if (size >= threshold) { int newCapacity = data.length * 2; if (newCapacity <= MAXIMUM_CAPACITY) { ensureCapacity(newCapacity); } } } /** * Changes the size of the data structure to the capacity proposed. * * @param newCapacity the new capacity of the array (a power of two, less or equal to max) */ protected void ensureCapacity(int newCapacity) { int oldCapacity = data.length; if (newCapacity <= oldCapacity) { return; } if (size == 0) { threshold = calculateThreshold(newCapacity, loadFactor); data = new HashEntry[newCapacity]; } else { HashEntry oldEntries[] = data; HashEntry newEntries[] = new HashEntry[newCapacity]; modCount++; for (int i = oldCapacity - 1; i >= 0; i--) { HashEntry entry = oldEntries[i]; if (entry != null) { oldEntries[i] = null; // gc do { HashEntry next = entry.next; int index = hashIndex(entry.hashCode, newCapacity); entry.next = newEntries[index]; newEntries[index] = entry; entry = next; } while (entry != null); } } threshold = calculateThreshold(newCapacity, loadFactor); data = newEntries; } } /** * Calculates the new capacity of the map. * This implementation normalizes the capacity to a power of two. * * @param proposedCapacity the proposed capacity * @return the normalized new capacity */ protected int calculateNewCapacity(int proposedCapacity) { int newCapacity = 1; if (proposedCapacity > MAXIMUM_CAPACITY) { newCapacity = MAXIMUM_CAPACITY; } else { while (newCapacity < proposedCapacity) { newCapacity <<= 1; // multiply by two } if (newCapacity > MAXIMUM_CAPACITY) { newCapacity = MAXIMUM_CAPACITY; } } return newCapacity; } /** * Calculates the new threshold of the map, where it will be resized. * This implementation uses the load factor. * * @param newCapacity the new capacity * @param factor the load factor * @return the new resize threshold */ protected int calculateThreshold(int newCapacity, float factor) { return (int) (newCapacity * factor); } //----------------------------------------------------------------------- /** * Gets the next field from a HashEntry. * Used in subclasses that have no visibility of the field. * * @param entry the entry to query, must not be null * @return the next field of the entry * @throws NullPointerException if the entry is null * @since Commons Collections 3.1 */ protected HashEntry entryNext(HashEntry entry) { return entry.next; } /** * Gets the hashCode field from a HashEntry. * Used in subclasses that have no visibility of the field. * * @param entry the entry to query, must not be null * @return the hashCode field of the entry * @throws NullPointerException if the entry is null * @since Commons Collections 3.1 */ protected int entryHashCode(HashEntry entry) { return entry.hashCode; } /** * Gets the key field from a HashEntry. * Used in subclasses that have no visibility of the field. * * @param entry the entry to query, must not be null * @return the key field of the entry * @throws NullPointerException if the entry is null * @since Commons Collections 3.1 */ protected K entryKey(HashEntry entry) { return entry.key; } /** * Gets the value field from a HashEntry. * Used in subclasses that have no visibility of the field. * * @param entry the entry to query, must not be null * @return the value field of the entry * @throws NullPointerException if the entry is null * @since Commons Collections 3.1 */ protected V entryValue(HashEntry entry) { return entry.value; } //----------------------------------------------------------------------- /** * Gets an iterator over the map. * Changes made to the iterator affect this map. *

* A MapIterator returns the keys in the map. It also provides convenient * methods to get the key and value, and set the value. * It avoids the need to create an entrySet/keySet/values object. * It also avoids creating the Map.Entry object. * * @return the map iterator */ public MapIterator mapIterator() { if (size == 0) { return EmptyMapIterator.INSTANCE; } return new HashMapIterator(this); } /** * MapIterator implementation. */ protected static class HashMapIterator extends HashIterator implements MapIterator { protected HashMapIterator(AbstractHashedMap parent) { super(parent); } public K next() { return super.nextEntry().getKey(); } public K getKey() { HashEntry current = currentEntry(); if (current == null) { throw new IllegalStateException(AbstractHashedMap.GETKEY_INVALID); } return current.getKey(); } public V getValue() { HashEntry current = currentEntry(); if (current == null) { throw new IllegalStateException(AbstractHashedMap.GETVALUE_INVALID); } return current.getValue(); } public V setValue(V value) { HashEntry current = currentEntry(); if (current == null) { throw new IllegalStateException(AbstractHashedMap.SETVALUE_INVALID); } return current.setValue(value); } } //----------------------------------------------------------------------- /** * Gets the entrySet view of the map. * Changes made to the view affect this map. * To simply iterate through the entries, use {@link #mapIterator()}. * * @return the entrySet view */ public Set> entrySet() { if (entrySet == null) { entrySet = new EntrySet(this); } return entrySet; } /** * Creates an entry set iterator. * Subclasses can override this to return iterators with different properties. * * @return the entrySet iterator */ protected Iterator> createEntrySetIterator() { if (size() == 0) { return EmptyIterator.INSTANCE; } return new EntrySetIterator(this); } /** * EntrySet implementation. */ protected static class EntrySet extends AbstractSet> { /** * The parent map */ protected final AbstractHashedMap parent; protected EntrySet(AbstractHashedMap parent) { super(); this.parent = parent; } public int size() { return parent.size(); } public void clear() { parent.clear(); } public boolean contains(Map.Entry entry) { Map.Entry e = entry; Entry match = parent.getEntry(e.getKey()); return (match != null && match.equals(e)); } public boolean remove(Object obj) { if (obj instanceof Map.Entry == false) { return false; } if (contains(obj) == false) { return false; } Map.Entry entry = (Map.Entry) obj; K key = entry.getKey(); parent.remove(key); return true; } public Iterator> iterator() { return parent.createEntrySetIterator(); } } /** * EntrySet iterator. */ protected static class EntrySetIterator extends HashIterator implements Iterator> { protected EntrySetIterator(AbstractHashedMap parent) { super(parent); } public HashEntry next() { return super.nextEntry(); } } //----------------------------------------------------------------------- /** * Gets the keySet view of the map. * Changes made to the view affect this map. * To simply iterate through the keys, use {@link #mapIterator()}. * * @return the keySet view */ public Set keySet() { if (keySet == null) { keySet = new KeySet(this); } return keySet; } /** * Creates a key set iterator. * Subclasses can override this to return iterators with different properties. * * @return the keySet iterator */ protected Iterator createKeySetIterator() { if (size() == 0) { return EmptyIterator.INSTANCE; } return new KeySetIterator(this); } /** * KeySet implementation. */ protected static class KeySet extends AbstractSet { /** * The parent map */ protected final AbstractHashedMap parent; protected KeySet(AbstractHashedMap parent) { super(); this.parent = parent; } public int size() { return parent.size(); } public void clear() { parent.clear(); } public boolean contains(Object key) { return parent.containsKey(key); } public boolean remove(Object key) { boolean result = parent.containsKey(key); parent.remove(key); return result; } public Iterator iterator() { return parent.createKeySetIterator(); } } /** * KeySet iterator. */ protected static class KeySetIterator extends HashIterator implements Iterator { protected KeySetIterator(AbstractHashedMap parent) { super(parent); } public K next() { return super.nextEntry().getKey(); } } //----------------------------------------------------------------------- /** * Gets the values view of the map. * Changes made to the view affect this map. * To simply iterate through the values, use {@link #mapIterator()}. * * @return the values view */ public Collection values() { if (values == null) { values = new Values(this); } return values; } /** * Creates a values iterator. * Subclasses can override this to return iterators with different properties. * * @return the values iterator */ protected Iterator createValuesIterator() { if (size() == 0) { return EmptyIterator.INSTANCE; } return new ValuesIterator(this); } /** * Values implementation. */ protected static class Values extends AbstractCollection { /** * The parent map */ protected final AbstractHashedMap parent; protected Values(AbstractHashedMap parent) { super(); this.parent = parent; } public int size() { return parent.size(); } public void clear() { parent.clear(); } public boolean contains(Object value) { return parent.containsValue(value); } public Iterator iterator() { return parent.createValuesIterator(); } } /** * Values iterator. */ protected static class ValuesIterator extends HashIterator implements Iterator { protected ValuesIterator(AbstractHashedMap parent) { super(parent); } public V next() { return super.nextEntry().getValue(); } } //----------------------------------------------------------------------- /** * HashEntry used to store the data. *

* If you subclass AbstractHashedMap but not HashEntry * then you will not be able to access the protected fields. * The entryXxx() methods on AbstractHashedMap exist * to provide the necessary access. */ protected static class HashEntry implements Map.Entry, KeyValue { /** * The next entry in the hash chain */ protected HashEntry next; /** * The hash code of the key */ protected int hashCode; /** * The key */ private K key; /** * The value */ private V value; protected HashEntry(HashEntry next, int hashCode, K key, V value) { super(); this.next = next; this.hashCode = hashCode; this.key = key; this.value = value; } public K getKey() { return key; } public void setKey(K key) { this.key = key; } public V getValue() { return value; } public V setValue(V value) { V old = this.value; this.value = value; return old; } public boolean equals(Object obj) { if (obj == this) { return true; } if (obj instanceof Map.Entry == false) { return false; } Map.Entry other = (Map.Entry) obj; return (getKey() == null ? other.getKey() == null : getKey().equals(other.getKey())) && (getValue() == null ? other.getValue() == null : getValue().equals(other.getValue())); } public int hashCode() { return (getKey() == null ? 0 : getKey().hashCode()) ^ (getValue() == null ? 0 : getValue().hashCode()); } public String toString() { return new StringBuffer().append(getKey()).append('=').append(getValue()).toString(); } } /** * Base Iterator */ protected static abstract class HashIterator { /** * The parent map */ protected final AbstractHashedMap parent; /** * The current index into the array of buckets */ protected int hashIndex; /** * The last returned entry */ protected HashEntry last; /** * The next entry */ protected HashEntry next; /** * The modification count expected */ protected int expectedModCount; protected HashIterator(AbstractHashedMap parent) { super(); this.parent = parent; HashEntry[] data = parent.data; int i = data.length; HashEntry next = null; while (i > 0 && next == null) { next = data[--i]; } this.next = next; this.hashIndex = i; this.expectedModCount = parent.modCount; } public boolean hasNext() { return (next != null); } protected HashEntry nextEntry() { if (parent.modCount != expectedModCount) { throw new ConcurrentModificationException(); } HashEntry newCurrent = next; if (newCurrent == null) { throw new NoSuchElementException(AbstractHashedMap.NO_NEXT_ENTRY); } HashEntry[] data = parent.data; int i = hashIndex; HashEntry n = newCurrent.next; while (n == null && i > 0) { n = data[--i]; } next = n; hashIndex = i; last = newCurrent; return newCurrent; } protected HashEntry currentEntry() { return last; } public void remove() { if (last == null) { throw new IllegalStateException(AbstractHashedMap.REMOVE_INVALID); } if (parent.modCount != expectedModCount) { throw new ConcurrentModificationException(); } parent.remove(last.getKey()); last = null; expectedModCount = parent.modCount; } public String toString() { if (last != null) { return "Iterator[" + last.getKey() + "=" + last.getValue() + "]"; } else { return "Iterator[]"; } } } //----------------------------------------------------------------------- /** * Writes the map data to the stream. This method must be overridden if a * subclass must be setup before put() is used. *

* Serialization is not one of the JDK's nicest topics. Normal serialization will * initialise the superclass before the subclass. Sometimes however, this isn't * what you want, as in this case the put() method on read can be * affected by subclass state. *

* The solution adopted here is to serialize the state data of this class in * this protected method. This method must be called by the * writeObject() of the first serializable subclass. *

* Subclasses may override if they have a specific field that must be present * on read before this implementation will work. Generally, the read determines * what must be serialized here, if anything. * * @param out the output stream */ protected void doWriteObject(ObjectOutputStream out) throws IOException { out.writeFloat(loadFactor); out.writeInt(data.length); out.writeInt(size); for (MapIterator it = mapIterator(); it.hasNext();) { out.writeObject(it.next()); out.writeObject(it.getValue()); } } /** * Reads the map data from the stream. This method must be overridden if a * subclass must be setup before put() is used. *

* Serialization is not one of the JDK's nicest topics. Normal serialization will * initialise the superclass before the subclass. Sometimes however, this isn't * what you want, as in this case the put() method on read can be * affected by subclass state. *

* The solution adopted here is to deserialize the state data of this class in * this protected method. This method must be called by the * readObject() of the first serializable subclass. *

* Subclasses may override if the subclass has a specific field that must be present * before put() or calculateThreshold() will work correctly. * * @param in the input stream */ protected void doReadObject(ObjectInputStream in) throws IOException, ClassNotFoundException { loadFactor = in.readFloat(); int capacity = in.readInt(); int size = in.readInt(); init(); data = new HashEntry[capacity]; for (int i = 0; i < size; i++) { K key = (K) in.readObject(); V value = (V) in.readObject(); put(key, value); } threshold = calculateThreshold(data.length, loadFactor); } //----------------------------------------------------------------------- /** * Clones the map without cloning the keys or values. *

* To implement clone(), a subclass must implement the * Cloneable interface and make this method public. * * @return a shallow clone */ protected Object clone() { try { AbstractHashedMap cloned = (AbstractHashedMap) super.clone(); cloned.data = new HashEntry[data.length]; cloned.entrySet = null; cloned.keySet = null; cloned.values = null; cloned.modCount = 0; cloned.size = 0; cloned.init(); cloned.putAll(this); return cloned; } catch (CloneNotSupportedException ex) { return null; // should never happen } } /** * Compares this map with another. * * @param obj the object to compare to * @return true if equal */ public boolean equals(Object obj) { if (obj == this) { return true; } if (obj instanceof Map == false) { return false; } Map map = (Map) obj; if (map.size() != size()) { return false; } MapIterator it = mapIterator(); try { while (it.hasNext()) { Object key = it.next(); Object value = it.getValue(); if (value == null) { if (map.get(key) != null || map.containsKey(key) == false) { return false; } } else { if (value.equals(map.get(key)) == false) { return false; } } } } catch (ClassCastException ignored) { return false; } catch (NullPointerException ignored) { return false; } return true; } /** * Gets the standard Map hashCode. * * @return the hash code defined in the Map interface */ public int hashCode() { int total = 0; Iterator it = createEntrySetIterator(); while (it.hasNext()) { total += it.next().hashCode(); } return total; } /** * Gets the map as a String. * * @return a string version of the map */ public String toString() { if (size() == 0) { return "{}"; } StringBuffer buf = new StringBuffer(32 * size()); buf.append('{'); MapIterator it = mapIterator(); boolean hasNext = it.hasNext(); while (hasNext) { Object key = it.next(); Object value = it.getValue(); buf.append(key == this ? "(this Map)" : key).append('=').append(value == this ? "(this Map)" : value); hasNext = it.hasNext(); if (hasNext) { buf.append(',').append(' '); } } buf.append('}'); return buf.toString(); } } collections-generic-4.01/src/java/org/apache/commons/collections15/map/AbstractMapDecorator.java0000644000175000017500000000720410464140763033147 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.map; import java.util.Collection; import java.util.Map; import java.util.Set; /** * Provides a base decorator that enables additional functionality to be added * to a Map via decoration. *

* Methods are forwarded directly to the decorated map. *

* This implementation does not perform any special processing with * {@link #entrySet()}, {@link #keySet()} or {@link #values()}. Instead * it simply returns the set/collection from the wrapped map. This may be * undesirable, for example if you are trying to write a validating * implementation it would provide a loophole around the validation. * But, you might want that loophole, so this class is kept simple. * * @author Daniel Rall * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:32 $ * @since Commons Collections 3.0 */ public abstract class AbstractMapDecorator implements Map { /** * The map to decorate */ protected transient Map map; /** * Constructor only used in deserialization, do not use otherwise. * * @since Commons Collections 3.1 */ protected AbstractMapDecorator() { super(); } /** * Constructor that wraps (not copies). * * @param map the map to decorate, must not be null * @throws IllegalArgumentException if the collection is null */ public AbstractMapDecorator(Map map) { if (map == null) { throw new IllegalArgumentException("Map must not be null"); } this.map = map; } /** * Gets the map being decorated. * * @return the decorated map */ protected Map getMap() { return map; } //----------------------------------------------------------------------- public void clear() { map.clear(); } public boolean containsKey(Object key) { return map.containsKey(key); } public boolean containsValue(Object value) { return map.containsValue(value); } public Set> entrySet() { return map.entrySet(); } public V get(Object key) { return map.get(key); } public boolean isEmpty() { return map.isEmpty(); } public Set keySet() { return map.keySet(); } public V put(K key, V value) { return map.put(key, value); } public void putAll(Map mapToCopy) { map.putAll(mapToCopy); } public V remove(Object key) { return map.remove(key); } public int size() { return map.size(); } public Collection values() { return map.values(); } public boolean equals(Object object) { if (object == this) { return true; } return map.equals(object); } public int hashCode() { return map.hashCode(); } public String toString() { return map.toString(); } } collections-generic-4.01/src/java/org/apache/commons/collections15/map/PredicatedMap.java0000644000175000017500000001454310464140761031607 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.map; import org.apache.commons.collections15.Predicate; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.Iterator; import java.util.Map; /** * Decorates another Map to validate that additions * match a specified predicate. *

* This map exists to provide validation for the decorated map. * It is normally created to decorate an empty map. * If an object cannot be added to the map, an IllegalArgumentException is thrown. *

* One usage would be to ensure that no null keys are added to the map. *

Map map = PredicatedSet.decorate(new HashMap(), NotNullPredicate.INSTANCE, null);
*

* This class is Serializable from Commons Collections 3.1. * * @author Stephen Colebourne * @author Matt Hall, John Watkinson, Paul Jack * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:32 $ * @since Commons Collections 3.0 */ public class PredicatedMap extends AbstractInputCheckedMapDecorator implements Serializable { /** * Serialization version */ private static final long serialVersionUID = 7412622456128415156L; /** * The key predicate to use */ protected final Predicate keyPredicate; /** * The value predicate to use */ protected final Predicate valuePredicate; /** * Factory method to create a predicated (validating) map. *

* If there are any elements already in the list being decorated, they * are validated. * * @param map the map to decorate, must not be null * @param keyPredicate the predicate to validate the keys, null means no check * @param valuePredicate the predicate to validate to values, null means no check * @throws IllegalArgumentException if the map is null */ public static Map decorate(Map map, Predicate keyPredicate, Predicate valuePredicate) { return new PredicatedMap(map, keyPredicate, valuePredicate); } //----------------------------------------------------------------------- /** * Constructor that wraps (not copies). * * @param map the map to decorate, must not be null * @param keyPredicate the predicate to validate the keys, null means no check * @param valuePredicate the predicate to validate to values, null means no check * @throws IllegalArgumentException if the map is null */ protected PredicatedMap(Map map, Predicate keyPredicate, Predicate valuePredicate) { super(map); this.keyPredicate = keyPredicate; this.valuePredicate = valuePredicate; Iterator> it = map.entrySet().iterator(); while (it.hasNext()) { Map.Entry entry = it.next(); K key = entry.getKey(); V value = entry.getValue(); validate(key, value); } } //----------------------------------------------------------------------- /** * Write the map out using a custom routine. * * @param out the output stream * @throws IOException * @since Commons Collections 3.1 */ private void writeObject(ObjectOutputStream out) throws IOException { out.defaultWriteObject(); out.writeObject(map); } /** * Read the map in using a custom routine. * * @param in the input stream * @throws IOException * @throws ClassNotFoundException * @since Commons Collections 3.1 */ private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); map = (Map) in.readObject(); } //----------------------------------------------------------------------- /** * Validates a key value pair. * * @param key the key to validate * @param value the value to validate * @throws IllegalArgumentException if invalid */ protected void validate(K key, V value) { if (keyPredicate != null && keyPredicate.evaluate(key) == false) { throw new IllegalArgumentException("Cannot add key - Predicate rejected it"); } if (valuePredicate != null && valuePredicate.evaluate(value) == false) { throw new IllegalArgumentException("Cannot add value - Predicate rejected it"); } } /** * Override to validate an object set into the map via setValue. * * @param value the value to validate * @throws IllegalArgumentException if invalid * @since Commons Collections 3.1 */ protected V checkSetValue(V value) { if (valuePredicate.evaluate(value) == false) { throw new IllegalArgumentException("Cannot set value - Predicate rejected it"); } return value; } /** * Override to only return true when there is a value transformer. * * @return true if a value predicate is in use * @since Commons Collections 3.1 */ protected boolean isSetValueChecking() { return (valuePredicate != null); } //----------------------------------------------------------------------- public V put(K key, V value) { validate(key, value); return map.put(key, value); } public void putAll(Map mapToCopy) { Iterator it = mapToCopy.entrySet().iterator(); while (it.hasNext()) { Map.Entry entry = (Map.Entry) it.next(); K key = (K) entry.getKey(); V value = (V) entry.getValue(); validate(key, value); } map.putAll(mapToCopy); } } collections-generic-4.01/src/java/org/apache/commons/collections15/map/TransformedMap.java0000644000175000017500000001511710464140757032032 0ustar giovannigiovanni// TODO: Not yet converted, deprecated (by me). /* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.map; import org.apache.commons.collections15.Transformer; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.Iterator; import java.util.Map; /** * Decorates another Map to transform objects that are added. *

* The Map put methods and Map.Entry setValue method are affected by this class. * Thus objects must be removed or searched for using their transformed form. * For example, if the transformation converts Strings to Integers, you must * use the Integer form to remove objects. *

* This class is Serializable from Commons Collections 3.1. *

* Note: This class cannot support generics without breaking the Map contract. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:32 $ * @since Commons Collections 3.0 */ public class TransformedMap extends AbstractInputCheckedMapDecorator implements Serializable { /** * Serialization version */ private static final long serialVersionUID = 7023152376788900464L; /** * The transformer to use for the key */ protected final Transformer keyTransformer; /** * The transformer to use for the value */ protected final Transformer valueTransformer; /** * Factory method to create a transforming map. *

* If there are any elements already in the map being decorated, they * are NOT transformed. * * @param map the map to decorate, must not be null * @param keyTransformer the transformer to use for key conversion, null means no conversion * @param valueTransformer the transformer to use for value conversion, null means no conversion * @throws IllegalArgumentException if map is null */ public static Map decorate(Map map, Transformer keyTransformer, Transformer valueTransformer) { return new TransformedMap(map, keyTransformer, valueTransformer); } //----------------------------------------------------------------------- /** * Constructor that wraps (not copies). *

* If there are any elements already in the collection being decorated, they * are NOT transformed. * * @param map the map to decorate, must not be null * @param keyTransformer the transformer to use for key conversion, null means no conversion * @param valueTransformer the transformer to use for value conversion, null means no conversion * @throws IllegalArgumentException if map is null */ protected TransformedMap(Map map, Transformer keyTransformer, Transformer valueTransformer) { super(map); this.keyTransformer = keyTransformer; this.valueTransformer = valueTransformer; } //----------------------------------------------------------------------- /** * Write the map out using a custom routine. * * @param out the output stream * @throws IOException * @since Commons Collections 3.1 */ private void writeObject(ObjectOutputStream out) throws IOException { out.defaultWriteObject(); out.writeObject(map); } /** * Read the map in using a custom routine. * * @param in the input stream * @throws IOException * @throws ClassNotFoundException * @since Commons Collections 3.1 */ private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); map = (Map) in.readObject(); } //----------------------------------------------------------------------- /** * Transforms a key. *

* The transformer itself may throw an exception if necessary. * * @param object the object to transform * @throws the transformed object */ protected Object transformKey(Object object) { if (keyTransformer == null) { return object; } return keyTransformer.transform(object); } /** * Transforms a value. *

* The transformer itself may throw an exception if necessary. * * @param object the object to transform * @throws the transformed object */ protected Object transformValue(Object object) { if (valueTransformer == null) { return object; } return valueTransformer.transform(object); } /** * Transforms a map. *

* The transformer itself may throw an exception if necessary. * * @param map the map to transform * @throws the transformed object */ protected Map transformMap(Map map) { Map result = new LinkedMap(map.size()); for (Iterator it = map.entrySet().iterator(); it.hasNext();) { Map.Entry entry = (Map.Entry) it.next(); result.put(transformKey(entry.getKey()), transformValue(entry.getValue())); } return result; } /** * Override to transform the value when using setValue. * * @param value the value to transform * @return the transformed value * @since Commons Collections 3.1 */ protected Object checkSetValue(Object value) { return valueTransformer.transform(value); } /** * Override to only return true when there is a value transformer. * * @return true if a value transformer is in use * @since Commons Collections 3.1 */ protected boolean isSetValueChecking() { return (valueTransformer != null); } //----------------------------------------------------------------------- public Object put(Object key, Object value) { key = transformKey(key); value = transformValue(value); return getMap().put(key, value); } public void putAll(Map mapToCopy) { mapToCopy = transformMap(mapToCopy); getMap().putAll(mapToCopy); } } collections-generic-4.01/src/java/org/apache/commons/collections15/map/TypedSortedMap.java0000644000175000017500000000443310464140755032011 0ustar giovannigiovanni// TODO: Not yet converted, deprecated (by me). /* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.map; import org.apache.commons.collections15.functors.InstanceofPredicate; import java.util.SortedMap; /** * Decorates another SortedMap to validate that elements added * are of a specific type. *

* The validation of additions is performed via an instanceof test against * a specified Class. If an object cannot be added to the * collection, an IllegalArgumentException is thrown. *

* The returned implementation is Serializable from Commons Collections 3.1. * * @author Stephen Colebourne * @author Matt Hall, John Watkinson, Matthew Hawthorne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:32 $ * @since Commons Collections 3.0 * @deprecated no longer needed with Java generics. */ public class TypedSortedMap { /** * Factory method to create a typed sorted map. *

* If there are any elements already in the map being decorated, they * are validated. * * @param map the map to decorate, must not be null * @param keyType the type to allow as keys, must not be null * @param valueType the type to allow as values, must not be null * @throws IllegalArgumentException if list or type is null * @throws IllegalArgumentException if the list contains invalid elements */ public static SortedMap decorate(SortedMap map, Class keyType, Class valueType) { return new PredicatedSortedMap(map, InstanceofPredicate.getInstance(keyType), InstanceofPredicate.getInstance(valueType)); } /** * Restrictive constructor. */ protected TypedSortedMap() { } } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootcollections-generic-4.01/src/java/org/apache/commons/collections15/map/AbstractSortedMapDecorator.javacollections-generic-4.01/src/java/org/apache/commons/collections15/map/AbstractSortedMapDecorator.ja0000644000175000017500000000552410464140754034004 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.map; import java.util.Comparator; import java.util.SortedMap; /** * Provides a base decorator that enables additional functionality to be added * to a Map via decoration. *

* Methods are forwarded directly to the decorated map. *

* This implementation does not perform any special processing with the map views. * Instead it simply returns the set/collection from the wrapped map. This may be * undesirable, for example if you are trying to write a validating implementation * it would provide a loophole around the validation. * But, you might want that loophole, so this class is kept simple. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:32 $ * @since Commons Collections 3.0 */ public abstract class AbstractSortedMapDecorator extends AbstractMapDecorator implements SortedMap { /** * Constructor only used in deserialization, do not use otherwise. * * @since Commons Collections 3.1 */ protected AbstractSortedMapDecorator() { super(); } /** * Constructor that wraps (not copies). * * @param map the map to decorate, must not be null * @throws IllegalArgumentException if the collection is null */ public AbstractSortedMapDecorator(SortedMap map) { super(map); } /** * Gets the map being decorated. * * @return the decorated map */ protected SortedMap getSortedMap() { return (SortedMap) map; } //----------------------------------------------------------------------- public Comparator comparator() { return getSortedMap().comparator(); } public K firstKey() { return getSortedMap().firstKey(); } public SortedMap headMap(K toKey) { return getSortedMap().headMap(toKey); } public K lastKey() { return getSortedMap().lastKey(); } public SortedMap subMap(K fromKey, K toKey) { return getSortedMap().subMap(fromKey, toKey); } public SortedMap tailMap(K fromKey) { return getSortedMap().tailMap(fromKey); } } collections-generic-4.01/src/java/org/apache/commons/collections15/map/LazySortedMap.java0000644000175000017500000001142710464140762031642 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.map; import java.util.Comparator; import java.util.SortedMap; import org.apache.commons.collections15.Factory; import org.apache.commons.collections15.Transformer; /** * Decorates another SortedMap to create objects in the map on demand. *

* When the {@link #get(Object)} method is called with a key that does not * exist in the map, the factory is used to create the object. The created * object will be added to the map using the requested key. *

* For instance: *

 * Factory factory = new Factory() {
 *     public Object create() {
 *         return new Date();
 *     }
 * }
 * SortedMap lazy = Lazy.sortedMap(new HashMap(), factory);
 * Object obj = lazy.get("NOW");
 * 
*

* After the above code is executed, obj will contain * a new Date instance. Furthermore, that Date * instance is mapped to the "NOW" key in the map. *

* This class is Serializable from Commons Collections 3.1. * * @author Stephen Colebourne * @author Matt Hall, John Watkinson, Paul Jack * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:32 $ * @since Commons Collections 3.0 */ public class LazySortedMap extends LazyMap implements SortedMap { /** * Serialization version */ private static final long serialVersionUID = 2715322183617658933L; /** * Factory method to create a lazily instantiated sorted map. * * @param map the map to decorate, must not be null * @param factory the factory to use, must not be null * @throws IllegalArgumentException if map or factory is null */ public static SortedMap decorate(SortedMap map, Factory factory) { return new LazySortedMap(map, factory); } /** * Factory method to create a lazily instantiated sorted map. * * @param map Map to decorate, must not be null * @param transformer Transformer to use, must not be null * @throws IllegalArgumentException if map or transformer is null */ public static SortedMap decorate(SortedMap map, Transformer transformer) { return new LazySortedMap(map, transformer); } //----------------------------------------------------------------------- /** * Constructor that wraps (not copies). * * @param map the map to decorate, must not be null * @param factory the factory to use, must not be null * @throws IllegalArgumentException if map or factory is null */ protected LazySortedMap(SortedMap map, Factory factory) { super(map, factory); } /** * Constructor that wraps (not copies). * * @param map Map to decorate, must not be null * @param transformer Transformer to use, must not be null * @throws IllegalArgumentException if map or transformer is null */ protected LazySortedMap(SortedMap map, Transformer transformer) { super(map, transformer); } //----------------------------------------------------------------------- /** * Gets the map being decorated. * * @return the decorated map */ protected SortedMap getSortedMap() { return (SortedMap) map; } //----------------------------------------------------------------------- public K firstKey() { return getSortedMap().firstKey(); } public K lastKey() { return getSortedMap().lastKey(); } public Comparator comparator() { return getSortedMap().comparator(); } public SortedMap subMap(K fromKey, K toKey) { SortedMap map = getSortedMap().subMap(fromKey, toKey); return new LazySortedMap(map, transformer); } public SortedMap headMap(K toKey) { SortedMap map = getSortedMap().headMap(toKey); return new LazySortedMap(map, transformer); } public SortedMap tailMap(K fromKey) { SortedMap map = getSortedMap().tailMap(fromKey); return new LazySortedMap(map, transformer); } } collections-generic-4.01/src/java/org/apache/commons/collections15/map/UnmodifiableOrderedMap.java0000644000175000017500000001122410464140761033437 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.map; import org.apache.commons.collections15.MapIterator; import org.apache.commons.collections15.OrderedMap; import org.apache.commons.collections15.OrderedMapIterator; import org.apache.commons.collections15.Unmodifiable; import org.apache.commons.collections15.collection.UnmodifiableCollection; import org.apache.commons.collections15.iterators.UnmodifiableMapIterator; import org.apache.commons.collections15.iterators.UnmodifiableOrderedMapIterator; import org.apache.commons.collections15.set.UnmodifiableSet; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.Collection; import java.util.Map; import java.util.Set; /** * Decorates another OrderedMap to ensure it can't be altered. *

* This class is Serializable from Commons Collections 3.1. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:32 $ * @since Commons Collections 3.0 */ public final class UnmodifiableOrderedMap extends AbstractOrderedMapDecorator implements Unmodifiable, Serializable { /** * Serialization version */ private static final long serialVersionUID = 8136428161720526266L; /** * Factory method to create an unmodifiable sorted map. * * @param map the map to decorate, must not be null * @throws IllegalArgumentException if map is null */ public static OrderedMap decorate(OrderedMap map) { if (map instanceof Unmodifiable) { return map; } return new UnmodifiableOrderedMap(map); } //----------------------------------------------------------------------- /** * Constructor that wraps (not copies). * * @param map the map to decorate, must not be null * @throws IllegalArgumentException if map is null */ private UnmodifiableOrderedMap(OrderedMap map) { super(map); } //----------------------------------------------------------------------- /** * Write the map out using a custom routine. * * @param out the output stream * @throws IOException * @since Commons Collections 3.1 */ private void writeObject(ObjectOutputStream out) throws IOException { out.defaultWriteObject(); out.writeObject(map); } /** * Read the map in using a custom routine. * * @param in the input stream * @throws IOException * @throws ClassNotFoundException * @since Commons Collections 3.1 */ private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); map = (Map) in.readObject(); } //----------------------------------------------------------------------- public MapIterator mapIterator() { MapIterator it = getOrderedMap().mapIterator(); return UnmodifiableMapIterator.decorate(it); } public OrderedMapIterator orderedMapIterator() { OrderedMapIterator it = getOrderedMap().orderedMapIterator(); return UnmodifiableOrderedMapIterator.decorate(it); } public void clear() { throw new UnsupportedOperationException(); } public V put(K key, V value) { throw new UnsupportedOperationException(); } public void putAll(Map mapToCopy) { throw new UnsupportedOperationException(); } public V remove(Object key) { throw new UnsupportedOperationException(); } public Set> entrySet() { Set> set = super.entrySet(); return UnmodifiableEntrySet.decorate(set); } public Set keySet() { Set set = super.keySet(); return UnmodifiableSet.decorate(set); } public Collection values() { Collection coll = super.values(); return UnmodifiableCollection.decorate(coll); } } collections-generic-4.01/src/java/org/apache/commons/collections15/map/ReferenceMap.java0000644000175000017500000001545010464140761031437 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2002-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.map; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; /** * A Map implementation that allows mappings to be * removed by the garbage collector. *

* When you construct a ReferenceMap, you can specify what kind * of references are used to store the map's keys and values. * If non-hard references are used, then the garbage collector can remove * mappings if a key or value becomes unreachable, or if the JVM's memory is * running low. For information on how the different reference types behave, * see {@link java.lang.ref.Reference}. *

* Different types of references can be specified for keys and values. * The keys can be configured to be weak but the values hard, * in which case this class will behave like a * * WeakHashMap. However, you can also specify hard keys and * weak values, or any other combination. The default constructor uses * hard keys and soft values, providing a memory-sensitive cache. *

* This map is similar to * {@link org.apache.commons.collections15.map.ReferenceIdentityMap ReferenceIdentityMap}. * It differs in that keys and values in this class are compared using equals(). *

* This {@link java.util.Map} implementation does not allow null elements. * Attempting to add a null key or value to the map will raise a NullPointerException. *

* This implementation is not synchronized. * You can use {@link java.util.Collections#synchronizedMap} to * provide synchronized access to a ReferenceMap. * Remember that synchronization will not stop the garbage collecter removing entries. *

* All the available iterators can be reset back to the start by casting to * ResettableIterator and calling reset(). *

* NOTE: As from Commons Collections 3.1 this map extends AbstractReferenceMap * (previously it extended AbstractMap). As a result, the implementation is now * extensible and provides a MapIterator. * * @author Paul Jack * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:32 $ * @see java.lang.ref.Reference * @since Commons Collections 3.0 (previously in main package v2.1) */ public class ReferenceMap extends AbstractReferenceMap implements Serializable { /** * Serialization version */ private static final long serialVersionUID = 1555089888138299607L; /** * Constructs a new ReferenceMap that will * use hard references to keys and soft references to values. */ public ReferenceMap() { super(HARD, SOFT, DEFAULT_CAPACITY, DEFAULT_LOAD_FACTOR, false); } /** * Constructs a new ReferenceMap that will * use the specified types of references. * * @param keyType the type of reference to use for keys; * must be {@link #HARD}, {@link #SOFT}, {@link #WEAK} * @param valueType the type of reference to use for values; * must be {@link #HARD}, {@link #SOFT}, {@link #WEAK} */ public ReferenceMap(int keyType, int valueType) { super(keyType, valueType, DEFAULT_CAPACITY, DEFAULT_LOAD_FACTOR, false); } /** * Constructs a new ReferenceMap that will * use the specified types of references. * * @param keyType the type of reference to use for keys; * must be {@link #HARD}, {@link #SOFT}, {@link #WEAK} * @param valueType the type of reference to use for values; * must be {@link #HARD}, {@link #SOFT}, {@link #WEAK} * @param purgeValues should the value be automatically purged when the * key is garbage collected */ public ReferenceMap(int keyType, int valueType, boolean purgeValues) { super(keyType, valueType, DEFAULT_CAPACITY, DEFAULT_LOAD_FACTOR, purgeValues); } /** * Constructs a new ReferenceMap with the * specified reference types, load factor and initial * capacity. * * @param keyType the type of reference to use for keys; * must be {@link #HARD}, {@link #SOFT}, {@link #WEAK} * @param valueType the type of reference to use for values; * must be {@link #HARD}, {@link #SOFT}, {@link #WEAK} * @param capacity the initial capacity for the map * @param loadFactor the load factor for the map */ public ReferenceMap(int keyType, int valueType, int capacity, float loadFactor) { super(keyType, valueType, capacity, loadFactor, false); } /** * Constructs a new ReferenceMap with the * specified reference types, load factor and initial * capacity. * * @param keyType the type of reference to use for keys; * must be {@link #HARD}, {@link #SOFT}, {@link #WEAK} * @param valueType the type of reference to use for values; * must be {@link #HARD}, {@link #SOFT}, {@link #WEAK} * @param capacity the initial capacity for the map * @param loadFactor the load factor for the map * @param purgeValues should the value be automatically purged when the * key is garbage collected */ public ReferenceMap(int keyType, int valueType, int capacity, float loadFactor, boolean purgeValues) { super(keyType, valueType, capacity, loadFactor, purgeValues); } //----------------------------------------------------------------------- /** * Write the map out using a custom routine. */ private void writeObject(ObjectOutputStream out) throws IOException { out.defaultWriteObject(); doWriteObject(out); } /** * Read the map in using a custom routine. */ private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); doReadObject(in); } } ././@LongLink0000000000000000000000000000015500000000000011566 Lustar rootrootcollections-generic-4.01/src/java/org/apache/commons/collections15/map/AbstractInputCheckedMapDecorator.javacollections-generic-4.01/src/java/org/apache/commons/collections15/map/AbstractInputCheckedMapDecora0000644000175000017500000001574510464140764034003 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.map; import org.apache.commons.collections15.iterators.AbstractIteratorDecorator; import org.apache.commons.collections15.keyvalue.AbstractMapEntryDecorator; import org.apache.commons.collections15.set.AbstractSetDecorator; import java.lang.reflect.Array; import java.util.Iterator; import java.util.Map; import java.util.Set; /** * An abstract base class that simplifies the task of creating map decorators. *

* The Map API is very difficult to decorate correctly, and involves implementing * lots of different classes. This class exists to provide a simpler API. *

* Special hook methods are provided that are called when objects are added to * the map. By overriding these methods, the input can be validated or manipulated. * In addition to the main map methods, the entrySet is also affected, which is * the hardest part of writing map implementations. *

* This class is package-scoped, and may be withdrawn or replaced in future * versions of Commons Collections. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:32 $ * @since Commons Collections 3.1 */ abstract class AbstractInputCheckedMapDecorator extends AbstractMapDecorator { /** * Constructor only used in deserialization, do not use otherwise. */ protected AbstractInputCheckedMapDecorator() { super(); } /** * Constructor that wraps (not copies). * * @param map the map to decorate, must not be null * @throws IllegalArgumentException if map is null */ protected AbstractInputCheckedMapDecorator(Map map) { super(map); } //----------------------------------------------------------------------- /** * Hook method called when a value is being set using setValue. *

* An implementation may validate the value and throw an exception * or it may transform the value into another object. *

* This implementation returns the input value. * * @param value the value to check * @throws UnsupportedOperationException if the map may not be changed by setValue * @throws IllegalArgumentException if the specified value is invalid * @throws ClassCastException if the class of the specified value is invalid * @throws NullPointerException if the specified value is null and nulls are invalid */ protected abstract V checkSetValue(V value); /** * Hook method called to determine if checkSetValue has any effect. *

* An implementation should return false if the checkSetValue method * has no effect as this optimises the implementation. *

* This implementation returns true. */ protected boolean isSetValueChecking() { return true; } //----------------------------------------------------------------------- public Set> entrySet() { if (isSetValueChecking()) { return new EntrySet(map.entrySet(), this); } else { return map.entrySet(); } } //----------------------------------------------------------------------- /** * Implementation of an entry set that checks additions via setValue. */ static class EntrySet extends AbstractSetDecorator> { /** * The parent map */ private final AbstractInputCheckedMapDecorator parent; protected EntrySet(Set> set, AbstractInputCheckedMapDecorator parent) { super(set); this.parent = parent; } public Iterator> iterator() { return new EntrySetIterator(collection.iterator(), parent); } public Object[] toArray() { Object[] array = collection.toArray(); for (int i = 0; i < array.length; i++) { array[i] = new MapEntry((Map.Entry) array[i], parent); } return array; } public T[] toArray(T array[]) { Object[] result = array; if (array.length > 0) { // we must create a new array to handle multi-threaded situations // where another thread could access data before we decorate it result = (T[]) Array.newInstance(array.getClass().getComponentType(), 0); } result = collection.toArray(result); for (int i = 0; i < result.length; i++) { result[i] = new MapEntry((Map.Entry) result[i], parent); } // check to see if result should be returned straight if (result.length > array.length) { return (T[]) result; } // copy back into input array to fulfil the method contract System.arraycopy(result, 0, array, 0, result.length); if (array.length > result.length) { array[result.length] = null; } return (T[]) array; } } /** * Implementation of an entry set iterator that checks additions via setValue. */ static class EntrySetIterator extends AbstractIteratorDecorator> { /** * The parent map */ private final AbstractInputCheckedMapDecorator parent; protected EntrySetIterator(Iterator> iterator, AbstractInputCheckedMapDecorator parent) { super(iterator); this.parent = parent; } public Map.Entry next() { Map.Entry entry = iterator.next(); return new MapEntry(entry, parent); } } /** * Implementation of a map entry that checks additions via setValue. */ static class MapEntry extends AbstractMapEntryDecorator { /** * The parent map */ private final AbstractInputCheckedMapDecorator parent; protected MapEntry(Map.Entry entry, AbstractInputCheckedMapDecorator parent) { super(entry); this.parent = parent; } public V setValue(V value) { value = parent.checkSetValue(value); return entry.setValue(value); } } } collections-generic-4.01/src/java/org/apache/commons/collections15/map/LRUMap.java0000644000175000017500000003325410464140763030207 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.map; import org.apache.commons.collections15.BoundedMap; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.Map; /** * A Map implementation with a fixed maximum size which removes * the least recently used entry if an entry is added when full. *

* The least recently used algorithm works on the get and put operations only. * Iteration of any kind, including setting the value by iteration, does not * change the order. Queries such as containsKey and containsValue or access * via views also do not change the order. *

* The map implements OrderedMap and entries may be queried using * the bidirectional OrderedMapIterator. The order returned is * least recently used to most recently used. Iterators from map views can * also be cast to OrderedIterator if required. *

* All the available iterators can be reset back to the start by casting to * ResettableIterator and calling reset(). * * @author James Strachan * @author Morgan Delagrange * @author Stephen Colebourne * @author Mike Pettypiece * @author Matt Hall, John Watkinson, Mario Ivankovits * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:32 $ * @since Commons Collections 3.0 (previously in main package v1.0) */ public class LRUMap extends AbstractLinkedMap implements BoundedMap, Serializable, Cloneable { /** * Serialisation version */ static final long serialVersionUID = -612114643488955218L; /** * Default maximum size */ protected static final int DEFAULT_MAX_SIZE = 100; /** * Maximum size */ private transient int maxSize; /** * Scan behaviour */ private boolean scanUntilRemovable; /** * Constructs a new empty map with a maximum size of 100. */ public LRUMap() { this(DEFAULT_MAX_SIZE, DEFAULT_LOAD_FACTOR, false); } /** * Constructs a new, empty map with the specified maximum size. * * @param maxSize the maximum size of the map * @throws IllegalArgumentException if the maximum size is less than one */ public LRUMap(int maxSize) { this(maxSize, DEFAULT_LOAD_FACTOR); } /** * Constructs a new, empty map with the specified maximum size. * * @param maxSize the maximum size of the map * @param scanUntilRemovable scan until a removeable entry is found, default false * @throws IllegalArgumentException if the maximum size is less than one * @since Commons Collections 3.1 */ public LRUMap(int maxSize, boolean scanUntilRemovable) { this(maxSize, DEFAULT_LOAD_FACTOR, scanUntilRemovable); } /** * Constructs a new, empty map with the specified initial capacity and * load factor. * * @param maxSize the maximum size of the map, -1 for no limit, * @param loadFactor the load factor * @throws IllegalArgumentException if the maximum size is less than one * @throws IllegalArgumentException if the load factor is less than zero */ public LRUMap(int maxSize, float loadFactor) { this(maxSize, loadFactor, false); } /** * Constructs a new, empty map with the specified initial capacity and * load factor. * * @param maxSize the maximum size of the map, -1 for no limit, * @param loadFactor the load factor * @param scanUntilRemovable scan until a removeable entry is found, default false * @throws IllegalArgumentException if the maximum size is less than one * @throws IllegalArgumentException if the load factor is less than zero * @since Commons Collections 3.1 */ public LRUMap(int maxSize, float loadFactor, boolean scanUntilRemovable) { super((maxSize < 1 ? DEFAULT_CAPACITY : maxSize), loadFactor); if (maxSize < 1) { throw new IllegalArgumentException("LRUMap max size must be greater than 0"); } this.maxSize = maxSize; this.scanUntilRemovable = scanUntilRemovable; } /** * Constructor copying elements from another map. *

* The maximum size is set from the map's size. * * @param map the map to copy * @throws NullPointerException if the map is null * @throws IllegalArgumentException if the map is empty */ public LRUMap(Map map) { this(map, false); } /** * Constructor copying elements from another map. *

* The maximum size is set from the map's size. * * @param map the map to copy * @param scanUntilRemovable scan until a removeable entry is found, default false * @throws NullPointerException if the map is null * @throws IllegalArgumentException if the map is empty * @since Commons Collections 3.1 */ public LRUMap(Map map, boolean scanUntilRemovable) { this(map.size(), DEFAULT_LOAD_FACTOR, scanUntilRemovable); putAll(map); } //----------------------------------------------------------------------- /** * Gets the value mapped to the key specified. *

* This operation changes the position of the key in the map to the * most recently used position (first). * * @param key the key * @return the mapped value, null if no match */ public V get(Object key) { LinkEntry entry = (LinkEntry) getEntry(key); if (entry == null) { return null; } moveToMRU(entry); return entry.getValue(); } //----------------------------------------------------------------------- /** * Moves an entry to the MRU position at the end of the list. *

* This implementation moves the updated entry to the end of the list. * * @param entry the entry to update */ protected void moveToMRU(LinkEntry entry) { if (entry.after != header) { modCount++; // remove entry.before.after = entry.after; entry.after.before = entry.before; // add first entry.after = header; entry.before = header.before; header.before.after = entry; header.before = entry; } } /** * Updates an existing key-value mapping. *

* This implementation moves the updated entry to the top of the list * using {@link #moveToMRU(org.apache.commons.collections15.map.AbstractLinkedMap.LinkEntry)}. * * @param entry the entry to update * @param newValue the new value to store */ protected void updateEntry(HashEntry entry, V newValue) { moveToMRU((LinkEntry) entry); // handles modCount entry.setValue(newValue); } /** * Adds a new key-value mapping into this map. *

* This implementation checks the LRU size and determines whether to * discard an entry or not using {@link #removeLRU(org.apache.commons.collections15.map.AbstractLinkedMap.LinkEntry)}. *

* From Commons Collections 3.1 this method uses {@link #isFull()} rather * than accessing size and maxSize directly. * It also handles the scanUntilRemovable functionality. * * @param hashIndex the index into the data array to store at * @param hashCode the hash code of the key to add * @param key the key to add * @param value the value to add */ protected void addMapping(int hashIndex, int hashCode, K key, V value) { if (isFull()) { LinkEntry reuse = header.after; boolean removeLRUEntry = false; if (scanUntilRemovable) { while (reuse != header) { if (removeLRU(reuse)) { removeLRUEntry = true; break; } reuse = reuse.after; } } else { removeLRUEntry = removeLRU(reuse); } if (removeLRUEntry) { reuseMapping(reuse, hashIndex, hashCode, key, value); } else { super.addMapping(hashIndex, hashCode, key, value); } } else { super.addMapping(hashIndex, hashCode, key, value); } } /** * Reuses an entry by removing it and moving it to a new place in the map. *

* This method uses {@link #removeEntry}, {@link #reuseEntry} and {@link #addEntry}. * * @param entry the entry to reuse * @param hashIndex the index into the data array to store at * @param hashCode the hash code of the key to add * @param key the key to add * @param value the value to add */ protected void reuseMapping(LinkEntry entry, int hashIndex, int hashCode, K key, V value) { // find the entry before the entry specified in the hash table // remember that the parameters (except the first) refer to the new entry, // not the old one int removeIndex = hashIndex(entry.hashCode, data.length); HashEntry loop = data[removeIndex]; HashEntry previous = null; while (loop != entry) { previous = loop; loop = loop.next; } // reuse the entry modCount++; removeEntry(entry, removeIndex, previous); reuseEntry(entry, hashIndex, hashCode, key, value); addEntry(entry, hashIndex); } /** * Subclass method to control removal of the least recently used entry from the map. *

* This method exists for subclasses to override. A subclass may wish to * provide cleanup of resources when an entry is removed. For example: *

     * protected boolean removeLRU(LinkEntry entry) {
     *   releaseResources(entry.getValue());  // release resources held by entry
     *   return true;  // actually delete entry
     * }
     * 
*

* Alternatively, a subclass may choose to not remove the entry or selectively * keep certain LRU entries. For example: *

     * protected boolean removeLRU(LinkEntry entry) {
     *   if (entry.getKey().toString().startsWith("System.")) {
     *     return false;  // entry not removed from LRUMap
     *   } else {
     *     return true;  // actually delete entry
     *   }
     * }
     * 
* The effect of returning false is dependent on the scanUntilRemovable flag. * If the flag is true, the next LRU entry will be passed to this method and so on * until one returns false and is removed, or every entry in the map has been passed. * If the scanUntilRemovable flag is false, the map will exceed the maximum size. *

* NOTE: Commons Collections 3.0 passed the wrong entry to this method. * This is fixed in version 3.1 onwards. * * @param entry the entry to be removed */ protected boolean removeLRU(LinkEntry entry) { return true; } //----------------------------------------------------------------------- /** * Returns true if this map is full and no new mappings can be added. * * @return true if the map is full */ public boolean isFull() { return (size >= maxSize); } /** * Gets the maximum size of the map (the bound). * * @return the maximum number of elements the map can hold */ public int maxSize() { return maxSize; } /** * Whether this LRUMap will scan until a removable entry is found when the * map is full. * * @return true if this map scans * @since Commons Collections 3.1 */ public boolean isScanUntilRemovable() { return scanUntilRemovable; } //----------------------------------------------------------------------- /** * Clones the map without cloning the keys or values. * * @return a shallow clone */ public Object clone() { return super.clone(); } /** * Write the map out using a custom routine. */ private void writeObject(ObjectOutputStream out) throws IOException { out.defaultWriteObject(); doWriteObject(out); } /** * Read the map in using a custom routine. */ private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); doReadObject(in); } /** * Writes the data necessary for put() to work in deserialization. */ protected void doWriteObject(ObjectOutputStream out) throws IOException { out.writeInt(maxSize); super.doWriteObject(out); } /** * Reads the data necessary for put() to work in the superclass. */ protected void doReadObject(ObjectInputStream in) throws IOException, ClassNotFoundException { maxSize = in.readInt(); super.doReadObject(in); } } collections-generic-4.01/src/java/org/apache/commons/collections15/map/LazyMap.java0000644000175000017500000001320210464140755030454 0ustar giovannigiovanni// GenericsNote: Converted -- Using a Transformer instead of a Factory is no longer allowed. /* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.map; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.Map; import org.apache.commons.collections15.Factory; import org.apache.commons.collections15.Transformer; import org.apache.commons.collections15.functors.FactoryTransformer; /** * Decorates another Map to create objects in the map on demand. *

* When the {@link #get(Object)} method is called with a key that does not * exist in the map, the factory is used to create the object. The created * object will be added to the map using the requested key. *

* For instance: *

 * Factory factory = new Factory() {
 *     public Object create() {
 *         return new Date();
 *     }
 * }
 * Map lazy = Lazy.map(new HashMap(), factory);
 * Object obj = lazy.get("NOW");
 * 
*

* After the above code is executed, obj will contain * a new Date instance. Furthermore, that Date * instance is mapped to the "NOW" key in the map. *

* This class is Serializable from Commons Collections 3.1. * * @author Stephen Colebourne * @author Matt Hall, John Watkinson, Paul Jack * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:32 $ * @since Commons Collections 3.0 */ public class LazyMap extends AbstractMapDecorator implements Map, Serializable { /** * Serialization version */ private static final long serialVersionUID = 7990956402564206740L; /** * The factory to use to construct elements */ //protected final Factory factory; /** * The factory to use to construct elements */ protected final Transformer transformer; /** * Factory method to create a lazily instantiated map. * * @param map the map to decorate, must not be null * @param factory the factory to use, must not be null * @throws IllegalArgumentException if map or factory is null */ public static Map decorate(Map map, Factory factory) { return new LazyMap(map, factory); } /** * Factory method to create a lazily instantiated map. * * @param map Map to decorate, must not be null * @param transformer Transformer to use, must not be null * @throws IllegalArgumentException if map or transformer is null */ public static Map decorate(Map map, Transformer transformer) { return new LazyMap(map, transformer); } //----------------------------------------------------------------------- /** * Constructor that wraps (not copies). * * @param map the map to decorate, must not be null * @param factory the factory to use, must not be null * @throws IllegalArgumentException if map or factory is null */ protected LazyMap(Map map, Factory factory) { super(map); if (factory == null) { throw new IllegalArgumentException("Factory must not be null"); } this.transformer = new FactoryTransformer(factory); } /** * Constructor that wraps (not copies). * * @param map Map to decorate, must not be null * @param transformer Transformer to use, must not be null * @throws IllegalArgumentException if map or factory is null */ protected LazyMap(Map map, Transformer transformer) { super(map); if (transformer == null) { throw new IllegalArgumentException("Transformer must not be null"); } this.transformer = transformer; } //----------------------------------------------------------------------- /** * Write the map out using a custom routine. * * @param out the output stream * @throws IOException * @since Commons Collections 3.1 */ private void writeObject(ObjectOutputStream out) throws IOException { out.defaultWriteObject(); out.writeObject(map); } /** * Read the map in using a custom routine. * * @param in the input stream * @throws IOException * @throws ClassNotFoundException * @since Commons Collections 3.1 */ private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); map = (Map) in.readObject(); } //----------------------------------------------------------------------- public V get(Object key) { // create value for key if key is not currently in the map if (map.containsKey(key) == false) { V value = this.transformer.transform((K) key); map.put((K) key, value); return value; } return map.get(key); } // no need to wrap keySet, entrySet or values as they are views of // existing map entries - you can't do a map-style get on them. } collections-generic-4.01/src/java/org/apache/commons/collections15/map/FixedSizeMap.java0000644000175000017500000001173010464140756031434 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.map; import org.apache.commons.collections15.BoundedMap; import org.apache.commons.collections15.collection.UnmodifiableCollection; import org.apache.commons.collections15.set.UnmodifiableSet; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.Collection; import java.util.Iterator; import java.util.Map; import java.util.Set; /** * Decorates another Map to fix the size, preventing add/remove. *

* Any action that would change the size of the map is disallowed. * The put method is allowed to change the value associated with an existing * key however. *

* If trying to remove or clear the map, an UnsupportedOperationException is * thrown. If trying to put a new mapping into the map, an * IllegalArgumentException is thrown. This is because the put method can * succeed if the mapping's key already exists in the map, so the put method * is not always unsupported. *

* This class is Serializable from Commons Collections 3.1. * * @author Stephen Colebourne * @author Matt Hall, John Watkinson, Paul Jack * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:32 $ * @since Commons Collections 3.0 */ public class FixedSizeMap extends AbstractMapDecorator implements Map, BoundedMap, Serializable { /** * Serialization version */ private static final long serialVersionUID = 7450927208116179316L; /** * Factory method to create a fixed size map. * * @param map the map to decorate, must not be null * @throws IllegalArgumentException if map is null */ public static Map decorate(Map map) { return new FixedSizeMap(map); } //----------------------------------------------------------------------- /** * Constructor that wraps (not copies). * * @param map the map to decorate, must not be null * @throws IllegalArgumentException if map is null */ protected FixedSizeMap(Map map) { super(map); } //----------------------------------------------------------------------- /** * Write the map out using a custom routine. * * @param out the output stream * @throws IOException * @since Commons Collections 3.1 */ private void writeObject(ObjectOutputStream out) throws IOException { out.defaultWriteObject(); out.writeObject(map); } /** * Read the map in using a custom routine. * * @param in the input stream * @throws IOException * @throws ClassNotFoundException * @since Commons Collections 3.1 */ private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); map = (Map) in.readObject(); } //----------------------------------------------------------------------- public V put(K key, V value) { if (map.containsKey(key) == false) { throw new IllegalArgumentException("Cannot put new key/value pair - Map is fixed size"); } return map.put(key, value); } public void putAll(Map mapToCopy) { for (Iterator it = mapToCopy.keySet().iterator(); it.hasNext();) { if (mapToCopy.containsKey(it.next()) == false) { throw new IllegalArgumentException("Cannot put new key/value pair - Map is fixed size"); } } map.putAll(mapToCopy); } public void clear() { throw new UnsupportedOperationException("Map is fixed size"); } public V remove(Object key) { throw new UnsupportedOperationException("Map is fixed size"); } public Set> entrySet() { Set> set = map.entrySet(); // unmodifiable set will still allow modification via Map.Entry objects return UnmodifiableSet.decorate(set); } public Set keySet() { Set set = map.keySet(); return UnmodifiableSet.decorate(set); } public Collection values() { Collection coll = map.values(); return UnmodifiableCollection.decorate(coll); } public boolean isFull() { return true; } public int maxSize() { return size(); } } collections-generic-4.01/src/java/org/apache/commons/collections15/map/UnmodifiableEntrySet.java0000644000175000017500000001273410464140761033201 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.map; import org.apache.commons.collections15.Unmodifiable; import org.apache.commons.collections15.iterators.AbstractIteratorDecorator; import org.apache.commons.collections15.keyvalue.AbstractMapEntryDecorator; import org.apache.commons.collections15.set.AbstractSetDecorator; import java.lang.reflect.Array; import java.util.*; /** * Decorates a map entry Set to ensure it can't be altered. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:32 $ * @since Commons Collections 3.0 */ public final class UnmodifiableEntrySet extends AbstractSetDecorator> implements Unmodifiable { /** * Factory method to create an unmodifiable set of Map Entry objects. * * @param set the set to decorate, must not be null * @throws IllegalArgumentException if set is null */ public static Set> decorate(Set> set) { if (set instanceof Unmodifiable) { return set; } return new UnmodifiableEntrySet(set); } //----------------------------------------------------------------------- /** * Constructor that wraps (not copies). * * @param set the set to decorate, must not be null * @throws IllegalArgumentException if set is null */ private UnmodifiableEntrySet(Set> set) { super(set); } //----------------------------------------------------------------------- public boolean add(Map.Entry object) { throw new UnsupportedOperationException(); } public boolean addAll(Collection> coll) { throw new UnsupportedOperationException(); } public void clear() { throw new UnsupportedOperationException(); } public boolean remove(Object object) { throw new UnsupportedOperationException(); } public boolean removeAll(Collection coll) { throw new UnsupportedOperationException(); } public boolean retainAll(Collection coll) { throw new UnsupportedOperationException(); } //----------------------------------------------------------------------- public Iterator> iterator() { return new UnmodifiableEntrySetIterator(collection.iterator()); } public Object[] toArray() { Object[] array = collection.toArray(); for (int i = 0; i < array.length; i++) { array[i] = new UnmodifiableEntry((Map.Entry) array[i]); } return array; } public T[] toArray(T array[]) { T[] result = array; if (array.length > 0) { // we must create a new array to handle multi-threaded situations // where another thread could access data before we decorate it result = (T[]) Array.newInstance(array.getClass().getComponentType(), 0); } result = collection.toArray(result); Collection> newCollection = new ArrayList>(); for (int i = 0; i < result.length; i++) { // result[i] = new UnmodifiableEntry((Map.Entry) result[i]); newCollection.add(new UnmodifiableEntry((Map.Entry) result[i])); } result = newCollection.toArray(result); // check to see if result should be returned straight if (result.length > array.length) { return result; } // copy back into input array to fulfil the method contract System.arraycopy(result, 0, array, 0, result.length); if (array.length > result.length) { array[result.length] = null; } return array; } //----------------------------------------------------------------------- /** * Implementation of an entry set iterator. */ final static class UnmodifiableEntrySetIterator extends AbstractIteratorDecorator> { protected UnmodifiableEntrySetIterator(Iterator> iterator) { super(iterator); } public Map.Entry next() { Map.Entry entry = (Map.Entry) iterator.next(); return new UnmodifiableEntry(entry); } public void remove() { throw new UnsupportedOperationException(); } } //----------------------------------------------------------------------- /** * Implementation of a map entry that is unmodifiable. */ final static class UnmodifiableEntry extends AbstractMapEntryDecorator { protected UnmodifiableEntry(Map.Entry entry) { super(entry); } public V setValue(V obj) { throw new UnsupportedOperationException(); } } } collections-generic-4.01/src/java/org/apache/commons/collections15/map/SingletonMap.java0000644000175000017500000004022010464140756031500 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.map; import org.apache.commons.collections15.*; import org.apache.commons.collections15.iterators.SingletonIterator; import org.apache.commons.collections15.keyvalue.TiedMapEntry; import java.io.Serializable; import java.util.*; /** * A Map implementation that holds a single item and is fixed size. *

* The single key/value pair is specified at creation. * The map is fixed size so any action that would change the size is disallowed. * However, the put or setValue methods can change * the value associated with the key. *

* If trying to remove or clear the map, an UnsupportedOperationException is thrown. * If trying to put a new mapping into the map, an IllegalArgumentException is thrown. * The put method will only suceed if the key specified is the same as the * singleton key. *

* The key and value can be obtained by: *

    *
  • normal Map methods and views *
  • the MapIterator, see {@link #mapIterator()} *
  • the KeyValue interface (just cast - no object creation) *
* * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:32 $ * @since Commons Collections 3.1 */ public class SingletonMap implements OrderedMap, BoundedMap, KeyValue, Serializable, Cloneable { /** * Serialization version */ private static final long serialVersionUID = -8931271118676803261L; /** * Singleton key */ private final K key; /** * Singleton value */ private V value; /** * Constructor that creates a map of null to null. */ public SingletonMap() { super(); this.key = null; } /** * Constructor specifying the key and value. * * @param key the key to use * @param value the value to use */ public SingletonMap(K key, V value) { super(); this.key = key; this.value = value; } /** * Constructor specifying the key and value as a KeyValue. * * @param keyValue the key value pair to use */ public SingletonMap(KeyValue keyValue) { super(); this.key = keyValue.getKey(); this.value = keyValue.getValue(); } /** * Constructor specifying the key and value as a MapEntry. * * @param entry the key value pair to use */ public SingletonMap(Map.Entry entry) { super(); this.key = entry.getKey(); this.value = entry.getValue(); } /** * Constructor copying elements from another map. * * @param map the map to copy, must be size 1 * @throws NullPointerException if the map is null * @throws IllegalArgumentException if the size is not 1 */ public SingletonMap(Map map) { super(); if (map.size() != 1) { throw new IllegalArgumentException("The map size must be 1"); } Map.Entry entry = map.entrySet().iterator().next(); this.key = entry.getKey(); this.value = entry.getValue(); } // KeyValue //----------------------------------------------------------------------- /** * Gets the key. * * @return the key */ public K getKey() { return key; } /** * Gets the value. * * @return the value */ public V getValue() { return value; } /** * Sets the value. * * @param value the new value to set * @return the old value */ public V setValue(V value) { V old = this.value; this.value = value; return old; } // BoundedMap //----------------------------------------------------------------------- /** * Is the map currently full, always true. * * @return true always */ public boolean isFull() { return true; } /** * Gets the maximum size of the map, always 1. * * @return 1 always */ public int maxSize() { return 1; } // Map //----------------------------------------------------------------------- /** * Gets the value mapped to the key specified. * * @param key the key * @return the mapped value, null if no match */ public V get(Object key) { if (isEqualKey(key)) { return value; } return null; } /** * Gets the size of the map, always 1. * * @return the size of 1 */ public int size() { return 1; } /** * Checks whether the map is currently empty, which it never is. * * @return false always */ public boolean isEmpty() { return false; } //----------------------------------------------------------------------- /** * Checks whether the map contains the specified key. * * @param key the key to search for * @return true if the map contains the key */ public boolean containsKey(Object key) { return (isEqualKey(key)); } /** * Checks whether the map contains the specified value. * * @param value the value to search for * @return true if the map contains the key */ public boolean containsValue(Object value) { return (isEqualValue(value)); } //----------------------------------------------------------------------- /** * Puts a key-value mapping into this map where the key must match the existing key. *

* An IllegalArgumentException is thrown if the key does not match as the map * is fixed size. * * @param key the key to set, must be the key of the map * @param value the value to set * @return the value previously mapped to this key, null if none * @throws IllegalArgumentException if the key does not match */ public V put(K key, V value) { if (isEqualKey(key)) { return setValue(value); } throw new IllegalArgumentException("Cannot put new key/value pair - Map is fixed size singleton"); } /** * Puts the values from the specified map into this map. *

* The map must be of size 0 or size 1. * If it is size 1, the key must match the key of this map otherwise an * IllegalArgumentException is thrown. * * @param map the map to add, must be size 0 or 1, and the key must match * @throws NullPointerException if the map is null * @throws IllegalArgumentException if the key does not match */ public void putAll(Map map) { switch (map.size()) { case 0: return; case 1: Map.Entry entry = map.entrySet().iterator().next(); put(entry.getKey(), entry.getValue()); return; default: throw new IllegalArgumentException("The map size must be 0 or 1"); } } /** * Unsupported operation. * * @param key the mapping to remove * @return the value mapped to the removed key, null if key not in map * @throws UnsupportedOperationException always */ public V remove(Object key) { throw new UnsupportedOperationException(); } /** * Unsupported operation. */ public void clear() { throw new UnsupportedOperationException(); } //----------------------------------------------------------------------- /** * Gets the entrySet view of the map. * Changes made via setValue affect this map. * To simply iterate through the entries, use {@link #mapIterator()}. * * @return the entrySet view */ public Set> entrySet() { Map.Entry entry = new TiedMapEntry(this, getKey()); return Collections.singleton(entry); } /** * Gets the unmodifiable keySet view of the map. * Changes made to the view affect this map. * To simply iterate through the keys, use {@link #mapIterator()}. * * @return the keySet view */ public Set keySet() { return Collections.singleton(key); } /** * Gets the unmodifiable values view of the map. * Changes made to the view affect this map. * To simply iterate through the values, use {@link #mapIterator()}. * * @return the values view */ public Collection values() { return new SingletonValues(this); } /** * Gets an iterator over the map. * Changes made to the iterator using setValue affect this map. * The remove method is unsupported. *

* A MapIterator returns the keys in the map. It also provides convenient * methods to get the key and value, and set the value. * It avoids the need to create an entrySet/keySet/values object. * It also avoids creating the Map Entry object. * * @return the map iterator */ public MapIterator mapIterator() { return new SingletonMapIterator(this); } // OrderedMap //----------------------------------------------------------------------- /** * Obtains an OrderedMapIterator over the map. *

* A ordered map iterator is an efficient way of iterating over maps * in both directions. * * @return an ordered map iterator */ public OrderedMapIterator orderedMapIterator() { return new SingletonMapIterator(this); } /** * Gets the first (and only) key in the map. * * @return the key */ public K firstKey() { return getKey(); } /** * Gets the last (and only) key in the map. * * @return the key */ public K lastKey() { return getKey(); } /** * Gets the next key after the key specified, always null. * * @param key the next key * @return null always */ public K nextKey(K key) { return null; } /** * Gets the previous key before the key specified, always null. * * @param key the next key * @return null always */ public K previousKey(K key) { return null; } //----------------------------------------------------------------------- /** * Compares the specified key to the stored key. * * @param key the key to compare * @return true if equal */ protected boolean isEqualKey(Object key) { return (key == null ? getKey() == null : key.equals(getKey())); } /** * Compares the specified value to the stored value. * * @param value the value to compare * @return true if equal */ protected boolean isEqualValue(Object value) { return (value == null ? getValue() == null : value.equals(getValue())); } //----------------------------------------------------------------------- /** * SingletonMapIterator. */ static class SingletonMapIterator implements OrderedMapIterator, ResettableIterator { private final SingletonMap parent; private boolean hasNext = true; private boolean canGetSet = false; SingletonMapIterator(SingletonMap parent) { super(); this.parent = parent; } public boolean hasNext() { return hasNext; } public K next() { if (hasNext == false) { throw new NoSuchElementException(AbstractHashedMap.NO_NEXT_ENTRY); } hasNext = false; canGetSet = true; return parent.getKey(); } public boolean hasPrevious() { return (hasNext == false); } public K previous() { if (hasNext == true) { throw new NoSuchElementException(AbstractHashedMap.NO_PREVIOUS_ENTRY); } hasNext = true; return parent.getKey(); } public void remove() { throw new UnsupportedOperationException(); } public K getKey() { if (canGetSet == false) { throw new IllegalStateException(AbstractHashedMap.GETKEY_INVALID); } return parent.getKey(); } public V getValue() { if (canGetSet == false) { throw new IllegalStateException(AbstractHashedMap.GETVALUE_INVALID); } return parent.getValue(); } public V setValue(V value) { if (canGetSet == false) { throw new IllegalStateException(AbstractHashedMap.SETVALUE_INVALID); } return parent.setValue(value); } public void reset() { hasNext = true; } public String toString() { if (hasNext) { return "Iterator[]"; } else { return "Iterator[" + getKey() + "=" + getValue() + "]"; } } } /** * Values implementation for the SingletonMap. * This class is needed as values is a view that must update as the map updates. */ static class SingletonValues extends AbstractSet implements Serializable { private static final long serialVersionUID = -3689524741863047872L; private final SingletonMap parent; SingletonValues(SingletonMap parent) { super(); this.parent = parent; } public int size() { return 1; } public boolean isEmpty() { return false; } public boolean contains(Object object) { return parent.containsValue(object); } public void clear() { throw new UnsupportedOperationException(); } public Iterator iterator() { return new SingletonIterator(parent.getValue(), false); } } //----------------------------------------------------------------------- /** * Clones the map without cloning the key or value. * * @return a shallow clone */ public Object clone() { try { SingletonMap cloned = (SingletonMap) super.clone(); return cloned; } catch (CloneNotSupportedException ex) { throw new InternalError(); } } /** * Compares this map with another. * * @param obj the object to compare to * @return true if equal */ public boolean equals(Object obj) { if (obj == this) { return true; } if (obj instanceof Map == false) { return false; } Map other = (Map) obj; if (other.size() != 1) { return false; } Map.Entry entry = (Map.Entry) other.entrySet().iterator().next(); return isEqualKey(entry.getKey()) && isEqualValue(entry.getValue()); } /** * Gets the standard Map hashCode. * * @return the hash code defined in the Map interface */ public int hashCode() { return (getKey() == null ? 0 : getKey().hashCode()) ^ (getValue() == null ? 0 : getValue().hashCode()); } /** * Gets the map as a String. * * @return a string version of the map */ public String toString() { return new StringBuffer(128).append('{').append(getKey()).append('=').append(getValue()).append('}').toString(); } } collections-generic-4.01/src/java/org/apache/commons/collections15/map/IdentityMap.java0000644000175000017500000001336410464140763031336 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.map; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.Map; /** * A Map implementation that matches keys and values based * on == not equals(). *

* This map will violate the detail of various Map and map view contracts. * As a general rule, don't compare this map to other maps. * * @author java util HashMap * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:32 $ * @since Commons Collections 3.0 */ public class IdentityMap extends AbstractHashedMap implements Serializable, Cloneable { /** * Serialisation version */ private static final long serialVersionUID = 2028493495224302329L; /** * Constructs a new empty map with default size and load factor. */ public IdentityMap() { super(DEFAULT_CAPACITY, DEFAULT_LOAD_FACTOR, DEFAULT_THRESHOLD); } /** * Constructs a new, empty map with the specified initial capacity. * * @param initialCapacity the initial capacity * @throws IllegalArgumentException if the initial capacity is less than one */ public IdentityMap(int initialCapacity) { super(initialCapacity); } /** * Constructs a new, empty map with the specified initial capacity and * load factor. * * @param initialCapacity the initial capacity * @param loadFactor the load factor * @throws IllegalArgumentException if the initial capacity is less than one * @throws IllegalArgumentException if the load factor is less than zero */ public IdentityMap(int initialCapacity, float loadFactor) { super(initialCapacity, loadFactor); } /** * Constructor copying elements from another map. * * @param map the map to copy * @throws NullPointerException if the map is null */ public IdentityMap(Map map) { super(map); } //----------------------------------------------------------------------- /** * Gets the hash code for the key specified. * This implementation uses the identity hash code. * * @param key the key to get a hash code for * @return the hash code */ protected int hash(Object key) { return System.identityHashCode(key); } /** * Compares two keys for equals. * This implementation uses ==. * * @param key1 the first key to compare * @param key2 the second key to compare * @return true if equal by identity */ protected boolean isEqualKey(Object key1, Object key2) { return (key1 == key2); } /** * Compares two values for equals. * This implementation uses ==. * * @param value1 the first value to compare * @param value2 the second value to compare * @return true if equal by identity */ protected boolean isEqualValue(Object value1, Object value2) { return (value1 == value2); } /** * Creates an entry to store the data. * This implementation creates an IdentityEntry instance. * * @param next the next entry in sequence * @param hashCode the hash code to use * @param key the key to store * @param value the value to store * @return the newly created entry */ protected HashEntry createEntry(HashEntry next, int hashCode, K key, V value) { return new IdentityEntry(next, hashCode, key, value); } //----------------------------------------------------------------------- /** * HashEntry */ protected static class IdentityEntry extends HashEntry { protected IdentityEntry(HashEntry next, int hashCode, K key, V value) { super(next, hashCode, key, value); } public boolean equals(Object obj) { if (obj == this) { return true; } if (obj instanceof Map.Entry == false) { return false; } Map.Entry other = (Map.Entry) obj; return (getKey() == other.getKey()) && (getValue() == other.getValue()); } public int hashCode() { return System.identityHashCode(getKey()) ^ System.identityHashCode(getValue()); } } //----------------------------------------------------------------------- /** * Clones the map without cloning the keys or values. * * @return a shallow clone */ public Object clone() { return super.clone(); } /** * Write the map out using a custom routine. */ private void writeObject(ObjectOutputStream out) throws IOException { out.defaultWriteObject(); doWriteObject(out); } /** * Read the map in using a custom routine. */ private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); doReadObject(in); } } collections-generic-4.01/src/java/org/apache/commons/collections15/map/TransformedSortedMap.java0000644000175000017500000001041110464140756033202 0ustar giovannigiovanni// TODO: Not yet converted, deprecated (by me). /* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.map; import org.apache.commons.collections15.Transformer; import java.util.Comparator; import java.util.SortedMap; /** * Decorates another SortedMap to transform objects that are added. *

* The Map put methods and Map.Entry setValue method are affected by this class. * Thus objects must be removed or searched for using their transformed form. * For example, if the transformation converts Strings to Integers, you must * use the Integer form to remove objects. *

* This class is Serializable from Commons Collections 3.1. *

* Note: This class cannot support generics without breaking the Map contract. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:32 $ * @since Commons Collections 3.0 */ public class TransformedSortedMap extends TransformedMap implements SortedMap { /** * Serialization version */ private static final long serialVersionUID = -8751771676410385778L; /** * Factory method to create a transforming sorted map. *

* If there are any elements already in the map being decorated, they * are NOT transformed. * * @param map the map to decorate, must not be null * @param keyTransformer the predicate to validate the keys, null means no transformation * @param valueTransformer the predicate to validate to values, null means no transformation * @throws IllegalArgumentException if the map is null */ public static SortedMap decorate(SortedMap map, Transformer keyTransformer, Transformer valueTransformer) { return new TransformedSortedMap(map, keyTransformer, valueTransformer); } //----------------------------------------------------------------------- /** * Constructor that wraps (not copies). *

* If there are any elements already in the collection being decorated, they * are NOT transformed.

* * @param map the map to decorate, must not be null * @param keyTransformer the predicate to validate the keys, null means no transformation * @param valueTransformer the predicate to validate to values, null means no transformation * @throws IllegalArgumentException if the map is null */ protected TransformedSortedMap(SortedMap map, Transformer keyTransformer, Transformer valueTransformer) { super(map, keyTransformer, valueTransformer); } //----------------------------------------------------------------------- /** * Gets the map being decorated. * * @return the decorated map */ protected SortedMap getSortedMap() { return (SortedMap) map; } //----------------------------------------------------------------------- public Object firstKey() { return getSortedMap().firstKey(); } public Object lastKey() { return getSortedMap().lastKey(); } public Comparator comparator() { return getSortedMap().comparator(); } public SortedMap subMap(Object fromKey, Object toKey) { SortedMap map = getSortedMap().subMap(fromKey, toKey); return new TransformedSortedMap(map, keyTransformer, valueTransformer); } public SortedMap headMap(Object toKey) { SortedMap map = getSortedMap().headMap(toKey); return new TransformedSortedMap(map, keyTransformer, valueTransformer); } public SortedMap tailMap(Object fromKey) { SortedMap map = getSortedMap().tailMap(fromKey); return new TransformedSortedMap(map, keyTransformer, valueTransformer); } } collections-generic-4.01/src/java/org/apache/commons/collections15/map/CaseInsensitiveMap.java0000644000175000017500000001253610464140763032641 0ustar giovannigiovanni// GenericsNote: Converted -- refactored heavily, and now must be a map of String -> ?. /* * Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.map; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.Iterator; import java.util.Map; import java.util.Set; /** * A case-insensitive Map. *

* As entries are added to the map, keys are converted to all lowercase. A new * key is compared to existing keys by comparing newKey.toLower() * to the lowercase values in the current KeySet. *

* Null keys are supported. *

* The keySet() method returns all lowercase keys, or nulls. *

* Example: *


 *  Map map = new CaseInsensitiveMap();
 *  map.put("One", "One");
 *  map.put("Two", "Two");
 *  map.put(null, "Three");
 *  map.put("one", "Four");
 * 
* creates a CaseInsensitiveMap with three entries.
* map.get(null) returns "Three" and map.get("ONE") * returns "Four". The Set returned by keySet() * equals {"one", "two", null}. * * @author Matt Hall, John Watkinson, Commons-Collections team * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:32 $ * @since Commons Collections 3.0 */ public class CaseInsensitiveMap extends AbstractHashedMap implements Serializable, Cloneable { /** * Serialisation version */ private static final long serialVersionUID = -7074655917369299456L; /** * Constructs a new empty map with default size and load factor. */ public CaseInsensitiveMap() { super(DEFAULT_CAPACITY, DEFAULT_LOAD_FACTOR, DEFAULT_THRESHOLD); } /** * Constructs a new, empty map with the specified initial capacity. * * @param initialCapacity the initial capacity * @throws IllegalArgumentException if the initial capacity is less than one */ public CaseInsensitiveMap(int initialCapacity) { super(initialCapacity); } /** * Constructs a new, empty map with the specified initial capacity and * load factor. * * @param initialCapacity the initial capacity * @param loadFactor the load factor * @throws IllegalArgumentException if the initial capacity is less than one * @throws IllegalArgumentException if the load factor is less than zero */ public CaseInsensitiveMap(int initialCapacity, float loadFactor) { super(initialCapacity, loadFactor); } /** * Constructor copying elements from another map. *

* Keys will be converted to lower case strings, which may cause * some entries to be removed (if string representation of keys differ * only by character case). * * @param map the map to copy * @throws NullPointerException if the map is null */ public CaseInsensitiveMap(Map map) { super(map); } //----------------------------------------------------------------------- /** * Converts keys to lower case. *

* Returns null if key is null. * * @param key the key convert * @return the converted key */ protected String convertKey(String key) { if (key != null) { return key.toString().toLowerCase(); } else { return null; } } @Override public V get(Object key) { if (!(key instanceof String)) { return super.get(key); } return super.get(convertKey((String) key)); } @Override public V put(String s, V v) { return super.put(convertKey(s), v); } @Override public void putAll(Map map) { Set entries = map.entrySet(); for (Iterator> iterator = entries.iterator(); iterator.hasNext();) { Entry entry = iterator.next(); put(entry.getKey(), entry.getValue()); } } //----------------------------------------------------------------------- /** * Clones the map without cloning the keys or values. * * @return a shallow clone */ public Object clone() { return super.clone(); } /** * Write the map out using a custom routine. */ private void writeObject(ObjectOutputStream out) throws IOException { out.defaultWriteObject(); doWriteObject(out); } /** * Read the map in using a custom routine. */ private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); doReadObject(in); } } collections-generic-4.01/src/java/org/apache/commons/collections15/map/FastHashMap.java0000644000175000017500000005136210464140765031250 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.map; import java.util.*; /** *

A customized implementation of java.util.HashMap designed * to operate in a multithreaded environment where the large majority of * method calls are read-only, instead of structural changes. When operating * in "fast" mode, read calls are non-synchronized and write calls perform the * following steps:

*
    *
  • Clone the existing collection *
  • Perform the modification on the clone *
  • Replace the existing collection with the (modified) clone *
*

When first created, objects of this class default to "slow" mode, where * all accesses of any type are synchronized but no cloning takes place. This * is appropriate for initially populating the collection, followed by a switch * to "fast" mode (by calling setFast(true)) after initialization * is complete.

*

*

NOTE: If you are creating and accessing a * HashMap only within a single thread, you should use * java.util.HashMap directly (with no synchronization), for * maximum performance.

*

*

NOTE: This class is not cross-platform. * Using it may cause unexpected failures on some architectures. * It suffers from the same problems as the double-checked locking idiom. * In particular, the instruction that clones the internal collection and the * instruction that sets the internal reference to the clone can be executed * or perceived out-of-order. This means that any read operation might fail * unexpectedly, as it may be reading the state of the internal collection * before the internal collection is fully formed. * For more information on the double-checked locking idiom, see the * * Double-Checked Locking Idiom Is Broken Declaration.

* * @author Craig R. McClanahan * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:32 $ * @since Commons Collections 1.0 */ public class FastHashMap extends HashMap { /** * The underlying map we are managing. */ protected HashMap map = null; /** * Are we currently operating in "fast" mode? */ protected boolean fast = false; // Constructors // ---------------------------------------------------------------------- /** * Construct an empty map. */ public FastHashMap() { super(); this.map = new HashMap(); } /** * Construct an empty map with the specified capacity. * * @param capacity the initial capacity of the empty map */ public FastHashMap(int capacity) { super(); this.map = new HashMap(capacity); } /** * Construct an empty map with the specified capacity and load factor. * * @param capacity the initial capacity of the empty map * @param factor the load factor of the new map */ public FastHashMap(int capacity, float factor) { super(); this.map = new HashMap(capacity, factor); } /** * Construct a new map with the same mappings as the specified map. * * @param map the map whose mappings are to be copied */ public FastHashMap(Map map) { super(); this.map = new HashMap(map); } // Property access // ---------------------------------------------------------------------- /** * Returns true if this map is operating in fast mode. * * @return true if this map is operating in fast mode */ public boolean getFast() { return (this.fast); } /** * Sets whether this map is operating in fast mode. * * @param fast true if this map should operate in fast mode */ public void setFast(boolean fast) { this.fast = fast; } // Map access // ---------------------------------------------------------------------- // These methods can forward straight to the wrapped Map in 'fast' mode. // (because they are query methods) /** * Return the value to which this map maps the specified key. Returns * null if the map contains no mapping for this key, or if * there is a mapping with a value of null. Use the * containsKey() method to disambiguate these cases. * * @param key the key whose value is to be returned * @return the value mapped to that key, or null */ public V get(Object key) { if (fast) { return (map.get(key)); } else { synchronized (map) { return (map.get(key)); } } } /** * Return the number of key-value mappings in this map. * * @return the current size of the map */ public int size() { if (fast) { return (map.size()); } else { synchronized (map) { return (map.size()); } } } /** * Return true if this map contains no mappings. * * @return is the map currently empty */ public boolean isEmpty() { if (fast) { return (map.isEmpty()); } else { synchronized (map) { return (map.isEmpty()); } } } /** * Return true if this map contains a mapping for the * specified key. * * @param key the key to be searched for * @return true if the map contains the key */ public boolean containsKey(Object key) { if (fast) { return (map.containsKey(key)); } else { synchronized (map) { return (map.containsKey(key)); } } } /** * Return true if this map contains one or more keys mapping * to the specified value. * * @param value the value to be searched for * @return true if the map contains the value */ public boolean containsValue(Object value) { if (fast) { return (map.containsValue(value)); } else { synchronized (map) { return (map.containsValue(value)); } } } // Map modification // ---------------------------------------------------------------------- // These methods perform special behaviour in 'fast' mode. // The map is cloned, updated and then assigned back. // See the comments at the top as to why this won't always work. /** * Associate the specified value with the specified key in this map. * If the map previously contained a mapping for this key, the old * value is replaced and returned. * * @param key the key with which the value is to be associated * @param value the value to be associated with this key * @return the value previously mapped to the key, or null */ public V put(K key, V value) { if (fast) { synchronized (this) { HashMap temp = (HashMap) map.clone(); V result = temp.put(key, value); map = temp; return (result); } } else { synchronized (map) { return (map.put(key, value)); } } } /** * Copy all of the mappings from the specified map to this one, replacing * any mappings with the same keys. * * @param in the map whose mappings are to be copied */ public void putAll(Map in) { if (fast) { synchronized (this) { HashMap temp = (HashMap) map.clone(); temp.putAll(in); map = temp; } } else { synchronized (map) { map.putAll(in); } } } /** * Remove any mapping for this key, and return any previously * mapped value. * * @param key the key whose mapping is to be removed * @return the value removed, or null */ public V remove(Object key) { if (fast) { synchronized (this) { HashMap temp = (HashMap) map.clone(); V result = temp.remove(key); map = temp; return (result); } } else { synchronized (map) { return (map.remove(key)); } } } /** * Remove all mappings from this map. */ public void clear() { if (fast) { synchronized (this) { map = new HashMap(); } } else { synchronized (map) { map.clear(); } } } // Basic object methods // ---------------------------------------------------------------------- /** * Compare the specified object with this list for equality. This * implementation uses exactly the code that is used to define the * list equals function in the documentation for the * Map.equals method. * * @param o the object to be compared to this list * @return true if the two maps are equal */ public boolean equals(Object o) { // Simple tests that require no synchronization if (o == this) { return (true); } else if (!(o instanceof Map)) { return (false); } Map mo = (Map) o; // Compare the two maps for equality if (fast) { if (mo.size() != map.size()) { return (false); } Iterator i = map.entrySet().iterator(); while (i.hasNext()) { Map.Entry e = (Map.Entry) i.next(); Object key = e.getKey(); Object value = e.getValue(); if (value == null) { if (!(mo.get(key) == null && mo.containsKey(key))) { return (false); } } else { if (!value.equals(mo.get(key))) { return (false); } } } return (true); } else { synchronized (map) { if (mo.size() != map.size()) { return (false); } Iterator i = map.entrySet().iterator(); while (i.hasNext()) { Map.Entry e = (Map.Entry) i.next(); Object key = e.getKey(); Object value = e.getValue(); if (value == null) { if (!(mo.get(key) == null && mo.containsKey(key))) { return (false); } } else { if (!value.equals(mo.get(key))) { return (false); } } } return (true); } } } /** * Return the hash code value for this map. This implementation uses * exactly the code that is used to define the list hash function in the * documentation for the Map.hashCode method. * * @return suitable integer hash code */ public int hashCode() { if (fast) { int h = 0; Iterator> i = map.entrySet().iterator(); while (i.hasNext()) { h += i.next().hashCode(); } return (h); } else { synchronized (map) { int h = 0; Iterator> i = map.entrySet().iterator(); while (i.hasNext()) { h += i.next().hashCode(); } return (h); } } } /** * Return a shallow copy of this FastHashMap instance. * The keys and values themselves are not copied. * * @return a clone of this map */ public FastHashMap clone() { FastHashMap results = null; if (fast) { results = new FastHashMap(map); } else { synchronized (map) { results = new FastHashMap(map); } } results.setFast(getFast()); return (results); } // Map views // ---------------------------------------------------------------------- /** * Return a collection view of the mappings contained in this map. Each * element in the returned collection is a Map.Entry. */ public Set> entrySet() { return new EntrySet(); } /** * Return a set view of the keys contained in this map. */ public Set keySet() { return new KeySet(); } /** * Return a collection view of the values contained in this map. */ public Collection values() { return new Values(); } // Map view inner classes // ---------------------------------------------------------------------- /** * Abstract collection implementation shared by keySet(), values() and entrySet(). */ private abstract class CollectionView implements Collection { public CollectionView() { } protected abstract Collection get(Map map); protected abstract E iteratorNext(Map.Entry entry); public void clear() { if (fast) { synchronized (FastHashMap.this) { map = new HashMap(); } } else { synchronized (map) { get(map).clear(); } } } public boolean remove(Object o) { if (fast) { synchronized (FastHashMap.this) { HashMap temp = (HashMap) map.clone(); boolean r = get(temp).remove(o); map = temp; return r; } } else { synchronized (map) { return get(map).remove(o); } } } public boolean removeAll(Collection o) { if (fast) { synchronized (FastHashMap.this) { HashMap temp = (HashMap) map.clone(); boolean r = get(temp).removeAll(o); map = temp; return r; } } else { synchronized (map) { return get(map).removeAll(o); } } } public boolean retainAll(Collection o) { if (fast) { synchronized (FastHashMap.this) { HashMap temp = (HashMap) map.clone(); boolean r = get(temp).retainAll(o); map = temp; return r; } } else { synchronized (map) { return get(map).retainAll(o); } } } public int size() { if (fast) { return get(map).size(); } else { synchronized (map) { return get(map).size(); } } } public boolean isEmpty() { if (fast) { return get(map).isEmpty(); } else { synchronized (map) { return get(map).isEmpty(); } } } public boolean contains(Object o) { if (fast) { return get(map).contains(o); } else { synchronized (map) { return get(map).contains(o); } } } public boolean containsAll(Collection o) { if (fast) { return get(map).containsAll(o); } else { synchronized (map) { return get(map).containsAll(o); } } } public T[] toArray(T[] o) { if (fast) { return get(map).toArray(o); } else { synchronized (map) { return get(map).toArray(o); } } } public Object[] toArray() { if (fast) { return get(map).toArray(); } else { synchronized (map) { return get(map).toArray(); } } } public boolean equals(Object o) { if (o == this) return true; if (fast) { return get(map).equals(o); } else { synchronized (map) { return get(map).equals(o); } } } public int hashCode() { if (fast) { return get(map).hashCode(); } else { synchronized (map) { return get(map).hashCode(); } } } public boolean add(E o) { throw new UnsupportedOperationException(); } public boolean addAll(Collection c) { throw new UnsupportedOperationException(); } public Iterator iterator() { return new CollectionViewIterator(); } private class CollectionViewIterator implements Iterator { private Map expected; private Map.Entry lastReturned = null; private Iterator iterator; public CollectionViewIterator() { this.expected = map; this.iterator = expected.entrySet().iterator(); } public boolean hasNext() { if (expected != map) { throw new ConcurrentModificationException(); } return iterator.hasNext(); } public E next() { if (expected != map) { throw new ConcurrentModificationException(); } lastReturned = (Map.Entry) iterator.next(); return iteratorNext(lastReturned); } public void remove() { if (lastReturned == null) { throw new IllegalStateException(); } if (fast) { synchronized (FastHashMap.this) { if (expected != map) { throw new ConcurrentModificationException(); } FastHashMap.this.remove(lastReturned.getKey()); lastReturned = null; expected = map; } } else { iterator.remove(); lastReturned = null; } } } } /** * Set implementation over the keys of the FastHashMap */ private class KeySet extends CollectionView implements Set { protected Collection get(Map map) { return map.keySet(); } protected K iteratorNext(Map.Entry entry) { return entry.getKey(); } } /** * Collection implementation over the values of the FastHashMap */ private class Values extends CollectionView { protected Collection get(Map map) { return map.values(); } protected V iteratorNext(Map.Entry entry) { return entry.getValue(); } } /** * Set implementation over the entries of the FastHashMap */ private class EntrySet extends CollectionView> implements Set> { protected Collection get(Map map) { return map.entrySet(); } protected Map.Entry iteratorNext(Map.Entry entry) { return entry; } } } collections-generic-4.01/src/java/org/apache/commons/collections15/map/FastTreeMap.java0000644000175000017500000005667110464140764031273 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.map; import java.util.*; /** *

A customized implementation of java.util.TreeMap designed * to operate in a multithreaded environment where the large majority of * method calls are read-only, instead of structural changes. When operating * in "fast" mode, read calls are non-synchronized and write calls perform the * following steps:

*
    *
  • Clone the existing collection *
  • Perform the modification on the clone *
  • Replace the existing collection with the (modified) clone *
*

When first created, objects of this class default to "slow" mode, where * all accesses of any type are synchronized but no cloning takes place. This * is appropriate for initially populating the collection, followed by a switch * to "fast" mode (by calling setFast(true)) after initialization * is complete.

*

*

NOTE: If you are creating and accessing a * TreeMap only within a single thread, you should use * java.util.TreeMap directly (with no synchronization), for * maximum performance.

*

*

NOTE: This class is not cross-platform. * Using it may cause unexpected failures on some architectures. * It suffers from the same problems as the double-checked locking idiom. * In particular, the instruction that clones the internal collection and the * instruction that sets the internal reference to the clone can be executed * or perceived out-of-order. This means that any read operation might fail * unexpectedly, as it may be reading the state of the internal collection * before the internal collection is fully formed. * For more information on the double-checked locking idiom, see the * * Double-Checked Locking Idiom Is Broken Declaration.

* * @author Craig R. McClanahan * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:32 $ * @since Commons Collections 1.0 */ public class FastTreeMap extends TreeMap { /** * The underlying map we are managing. */ protected TreeMap map = null; /** * Are we operating in "fast" mode? */ protected boolean fast = false; // Constructors // ---------------------------------------------------------------------- /** * Construct a an empty map. */ public FastTreeMap() { super(); this.map = new TreeMap(); } /** * Construct an empty map with the specified comparator. * * @param comparator the comparator to use for ordering tree elements */ public FastTreeMap(Comparator comparator) { super(); this.map = new TreeMap(comparator); } /** * Construct a new map with the same mappings as the specified map, * sorted according to the keys's natural order * * @param map the map whose mappings are to be copied */ public FastTreeMap(Map map) { super(); this.map = new TreeMap(map); } /** * Construct a new map with the same mappings as the specified map, * sorted according to the same ordering * * @param map the map whose mappings are to be copied */ public FastTreeMap(SortedMap map) { super(); this.map = new TreeMap(map); } // Property access // ---------------------------------------------------------------------- /** * Returns true if this map is operating in fast mode. * * @return true if this map is operating in fast mode */ public boolean getFast() { return (this.fast); } /** * Sets whether this map is operating in fast mode. * * @param fast true if this map should operate in fast mode */ public void setFast(boolean fast) { this.fast = fast; } // Map access // ---------------------------------------------------------------------- // These methods can forward straight to the wrapped Map in 'fast' mode. // (because they are query methods) /** * Return the value to which this map maps the specified key. Returns * null if the map contains no mapping for this key, or if * there is a mapping with a value of null. Use the * containsKey() method to disambiguate these cases. * * @param key the key whose value is to be returned * @return the value mapped to that key, or null */ public V get(Object key) { if (fast) { return (map.get(key)); } else { synchronized (map) { return (map.get(key)); } } } /** * Return the number of key-value mappings in this map. * * @return the current size of the map */ public int size() { if (fast) { return (map.size()); } else { synchronized (map) { return (map.size()); } } } /** * Return true if this map contains no mappings. * * @return is the map currently empty */ public boolean isEmpty() { if (fast) { return (map.isEmpty()); } else { synchronized (map) { return (map.isEmpty()); } } } /** * Return true if this map contains a mapping for the * specified key. * * @param key the key to be searched for * @return true if the map contains the key */ public boolean containsKey(Object key) { if (fast) { return (map.containsKey(key)); } else { synchronized (map) { return (map.containsKey(key)); } } } /** * Return true if this map contains one or more keys mapping * to the specified value. * * @param value the value to be searched for * @return true if the map contains the value */ public boolean containsValue(Object value) { if (fast) { return (map.containsValue(value)); } else { synchronized (map) { return (map.containsValue(value)); } } } /** * Return the comparator used to order this map, or null * if this map uses its keys' natural order. * * @return the comparator used to order the map, or null if natural order */ public Comparator comparator() { if (fast) { return (map.comparator()); } else { synchronized (map) { return (map.comparator()); } } } /** * Return the first (lowest) key currently in this sorted map. * * @return the first key in the map */ public K firstKey() { if (fast) { return (map.firstKey()); } else { synchronized (map) { return (map.firstKey()); } } } /** * Return the last (highest) key currently in this sorted map. * * @return the last key in the map */ public K lastKey() { if (fast) { return (map.lastKey()); } else { synchronized (map) { return (map.lastKey()); } } } // Map modification // ---------------------------------------------------------------------- // These methods perform special behaviour in 'fast' mode. // The map is cloned, updated and then assigned back. // See the comments at the top as to why this won't always work. /** * Associate the specified value with the specified key in this map. * If the map previously contained a mapping for this key, the old * value is replaced and returned. * * @param key the key with which the value is to be associated * @param value the value to be associated with this key * @return the value previously mapped to the key, or null */ public V put(K key, V value) { if (fast) { synchronized (this) { TreeMap temp = (TreeMap) map.clone(); V result = temp.put(key, value); map = temp; return (result); } } else { synchronized (map) { return (map.put(key, value)); } } } /** * Copy all of the mappings from the specified map to this one, replacing * any mappings with the same keys. * * @param in the map whose mappings are to be copied */ public void putAll(Map in) { if (fast) { synchronized (this) { TreeMap temp = (TreeMap) map.clone(); temp.putAll(in); map = temp; } } else { synchronized (map) { map.putAll(in); } } } /** * Remove any mapping for this key, and return any previously * mapped value. * * @param key the key whose mapping is to be removed * @return the value removed, or null */ public V remove(Object key) { if (fast) { synchronized (this) { TreeMap temp = (TreeMap) map.clone(); V result = temp.remove(key); map = temp; return (result); } } else { synchronized (map) { return (map.remove(key)); } } } /** * Remove all mappings from this map. */ public void clear() { if (fast) { synchronized (this) { map = new TreeMap(); } } else { synchronized (map) { map.clear(); } } } // Basic object methods // ---------------------------------------------------------------------- /** * Compare the specified object with this list for equality. This * implementation uses exactly the code that is used to define the * list equals function in the documentation for the * Map.equals method. * * @param o the object to be compared to this list * @return true if the two maps are equal */ public boolean equals(Object o) { // Simple tests that require no synchronization if (o == this) { return (true); } else if (!(o instanceof Map)) { return (false); } Map mo = (Map) o; // Compare the two maps for equality if (fast) { if (mo.size() != map.size()) { return (false); } Iterator i = map.entrySet().iterator(); while (i.hasNext()) { Map.Entry e = (Map.Entry) i.next(); Object key = e.getKey(); Object value = e.getValue(); if (value == null) { if (!(mo.get(key) == null && mo.containsKey(key))) { return (false); } } else { if (!value.equals(mo.get(key))) { return (false); } } } return (true); } else { synchronized (map) { if (mo.size() != map.size()) { return (false); } Iterator i = map.entrySet().iterator(); while (i.hasNext()) { Map.Entry e = (Map.Entry) i.next(); Object key = e.getKey(); Object value = e.getValue(); if (value == null) { if (!(mo.get(key) == null && mo.containsKey(key))) { return (false); } } else { if (!value.equals(mo.get(key))) { return (false); } } } return (true); } } } /** * Return the hash code value for this map. This implementation uses * exactly the code that is used to define the list hash function in the * documentation for the Map.hashCode method. * * @return a suitable integer hash code */ public int hashCode() { if (fast) { int h = 0; Iterator i = map.entrySet().iterator(); while (i.hasNext()) { h += i.next().hashCode(); } return (h); } else { synchronized (map) { int h = 0; Iterator i = map.entrySet().iterator(); while (i.hasNext()) { h += i.next().hashCode(); } return (h); } } } /** * Return a shallow copy of this FastTreeMap instance. * The keys and values themselves are not copied. * * @return a clone of this map */ public FastTreeMap clone() { FastTreeMap results = null; if (fast) { results = new FastTreeMap(map); } else { synchronized (map) { results = new FastTreeMap(map); } } results.setFast(getFast()); return (results); } // Sub map views // ---------------------------------------------------------------------- /** * Return a view of the portion of this map whose keys are strictly * less than the specified key. * * @param key Key higher than any in the returned map * @return a head map */ public SortedMap headMap(K key) { if (fast) { return (map.headMap(key)); } else { synchronized (map) { return (map.headMap(key)); } } } /** * Return a view of the portion of this map whose keys are in the * range fromKey (inclusive) to toKey (exclusive). * * @param fromKey Lower limit of keys for the returned map * @param toKey Upper limit of keys for the returned map * @return a sub map */ public SortedMap subMap(K fromKey, K toKey) { if (fast) { return (map.subMap(fromKey, toKey)); } else { synchronized (map) { return (map.subMap(fromKey, toKey)); } } } /** * Return a view of the portion of this map whose keys are greater than * or equal to the specified key. * * @param key Key less than or equal to any in the returned map * @return a tail map */ public SortedMap tailMap(K key) { if (fast) { return (map.tailMap(key)); } else { synchronized (map) { return (map.tailMap(key)); } } } // Map views // ---------------------------------------------------------------------- /** * Return a collection view of the mappings contained in this map. Each * element in the returned collection is a Map.Entry. */ public Set> entrySet() { return new EntrySet(); } /** * Return a set view of the keys contained in this map. */ public Set keySet() { return new KeySet(); } /** * Return a collection view of the values contained in this map. */ public Collection values() { return new Values(); } // Map view inner classes // ---------------------------------------------------------------------- /** * Abstract collection implementation shared by keySet(), values() and entrySet(). */ private abstract class CollectionView implements Collection { public CollectionView() { } protected abstract Collection get(Map map); protected abstract E iteratorNext(Map.Entry entry); public void clear() { if (fast) { synchronized (FastTreeMap.this) { map = new TreeMap(); } } else { synchronized (map) { get(map).clear(); } } } public boolean remove(Object o) { if (fast) { synchronized (FastTreeMap.this) { TreeMap temp = (TreeMap) map.clone(); boolean r = get(temp).remove(o); map = temp; return r; } } else { synchronized (map) { return get(map).remove(o); } } } public boolean removeAll(Collection o) { if (fast) { synchronized (FastTreeMap.this) { TreeMap temp = (TreeMap) map.clone(); boolean r = get(temp).removeAll(o); map = temp; return r; } } else { synchronized (map) { return get(map).removeAll(o); } } } public boolean retainAll(Collection o) { if (fast) { synchronized (FastTreeMap.this) { TreeMap temp = (TreeMap) map.clone(); boolean r = get(temp).retainAll(o); map = temp; return r; } } else { synchronized (map) { return get(map).retainAll(o); } } } public int size() { if (fast) { return get(map).size(); } else { synchronized (map) { return get(map).size(); } } } public boolean isEmpty() { if (fast) { return get(map).isEmpty(); } else { synchronized (map) { return get(map).isEmpty(); } } } public boolean contains(Object o) { if (fast) { return get(map).contains(o); } else { synchronized (map) { return get(map).contains(o); } } } public boolean containsAll(Collection o) { if (fast) { return get(map).containsAll(o); } else { synchronized (map) { return get(map).containsAll(o); } } } public T[] toArray(T[] o) { if (fast) { return get(map).toArray(o); } else { synchronized (map) { return get(map).toArray(o); } } } public Object[] toArray() { if (fast) { return get(map).toArray(); } else { synchronized (map) { return get(map).toArray(); } } } public boolean equals(Object o) { if (o == this) return true; if (fast) { return get(map).equals(o); } else { synchronized (map) { return get(map).equals(o); } } } public int hashCode() { if (fast) { return get(map).hashCode(); } else { synchronized (map) { return get(map).hashCode(); } } } public boolean add(E o) { throw new UnsupportedOperationException(); } public boolean addAll(Collection c) { throw new UnsupportedOperationException(); } public Iterator iterator() { return new CollectionViewIterator(); } private class CollectionViewIterator implements Iterator { private Map expected; private Map.Entry lastReturned = null; private Iterator> iterator; public CollectionViewIterator() { this.expected = map; this.iterator = expected.entrySet().iterator(); } public boolean hasNext() { if (expected != map) { throw new ConcurrentModificationException(); } return iterator.hasNext(); } public E next() { if (expected != map) { throw new ConcurrentModificationException(); } lastReturned = (Map.Entry) iterator.next(); return iteratorNext(lastReturned); } public void remove() { if (lastReturned == null) { throw new IllegalStateException(); } if (fast) { synchronized (FastTreeMap.this) { if (expected != map) { throw new ConcurrentModificationException(); } FastTreeMap.this.remove(lastReturned.getKey()); lastReturned = null; expected = map; } } else { iterator.remove(); lastReturned = null; } } } } /** * Set implementation over the keys of the FastTreeMap */ private class KeySet extends CollectionView implements Set { protected Collection get(Map map) { return map.keySet(); } protected K iteratorNext(Map.Entry entry) { return entry.getKey(); } } /** * Collection implementation over the values of the FastTreeMap */ private class Values extends CollectionView { protected Collection get(Map map) { return map.values(); } protected V iteratorNext(Map.Entry entry) { return entry.getValue(); } } /** * Set implementation over the entries of the FastTreeMap */ private class EntrySet extends CollectionView> implements Set> { protected Collection> get(Map map) { return map.entrySet(); } protected Map.Entry iteratorNext(Map.Entry entry) { return entry; } } } collections-generic-4.01/src/java/org/apache/commons/collections15/map/StaticBucketMap.java0000644000175000017500000005051710464140762032132 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2002-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.map; import org.apache.commons.collections15.KeyValue; import java.util.*; /** * A StaticBucketMap is an efficient, thread-safe implementation of * java.util.Map that performs well in in a highly * thread-contentious environment. The map supports very efficient * {@link #get(Object) get}, {@link #put(Object,Object) put}, * {@link #remove(Object) remove} and {@link #containsKey(Object) containsKey} * operations, assuming (approximate) uniform hashing and * that the number of entries does not exceed the number of buckets. If the * number of entries exceeds the number of buckets or if the hash codes of the * objects are not uniformly distributed, these operations have a worst case * scenario that is proportional to the number of elements in the map * (O(n)).

*

* Each bucket in the hash table has its own monitor, so two threads can * safely operate on the map at the same time, often without incurring any * monitor contention. This means that you don't have to wrap instances * of this class with {@link java.util.Collections#synchronizedMap(Map)}; * instances are already thread-safe. Unfortunately, however, this means * that this map implementation behaves in ways you may find disconcerting. * Bulk operations, such as {@link #putAll(Map) putAll} or the * {@link Collection#retainAll(Collection) retainAll} operation in collection * views, are not atomic. If two threads are simultaneously * executing *

*

 *   staticBucketMapInstance.putAll(map);
 * 
*

* and *

*

 *   staticBucketMapInstance.entrySet().removeAll(map.entrySet());
 * 
*

* then the results are generally random. Those two statement could cancel * each other out, leaving staticBucketMapInstance essentially * unchanged, or they could leave some random subset of map in * staticBucketMapInstance.

*

* Also, much like an encyclopedia, the results of {@link #size()} and * {@link #isEmpty()} are out-of-date as soon as they are produced.

*

* The iterators returned by the collection views of this class are not * fail-fast. They will never raise a * {@link java.util.ConcurrentModificationException}. Keys and values * added to the map after the iterator is created do not necessarily appear * during iteration. Similarly, the iterator does not necessarily fail to * return keys and values that were removed after the iterator was created.

*

* Finally, unlike {@link java.util.HashMap}-style implementations, this * class never rehashes the map. The number of buckets is fixed * at construction time and never altered. Performance may degrade if * you do not allocate enough buckets upfront.

*

* The {@link #atomic(Runnable)} method is provided to allow atomic iterations * and bulk operations; however, overuse of {@link #atomic(Runnable) atomic} * will basically result in a map that's slower than an ordinary synchronized * {@link java.util.HashMap}. *

* Use this class if you do not require reliable bulk operations and * iterations, or if you can make your own guarantees about how bulk * operations will affect the map.

* * @author Berin Loritsch * @author Gerhard Froehlich * @author Michael A. Smith * @author Paul Jack * @author Leo Sutic * @author Matt Hall, John Watkinson, Janek Bogucki * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:32 $ * @since Commons Collections 3.0 (previously in main package v2.1) */ public final class StaticBucketMap implements Map { /** * The default number of buckets to use */ private static final int DEFAULT_BUCKETS = 255; /** * The array of buckets, where the actual data is held */ private Node[] buckets; /** * The matching array of locks */ private Lock[] locks; /** * Initializes the map with the default number of buckets (255). */ public StaticBucketMap() { this(DEFAULT_BUCKETS); } /** * Initializes the map with a specified number of buckets. The number * of buckets is never below 17, and is always an odd number (StaticBucketMap * ensures this). The number of buckets is inversely proportional to the * chances for thread contention. The fewer buckets, the more chances for * thread contention. The more buckets the fewer chances for thread * contention. * * @param numBuckets the number of buckets for this map */ public StaticBucketMap(int numBuckets) { int size = Math.max(17, numBuckets); // Ensure that bucketSize is never a power of 2 (to ensure maximal distribution) if (size % 2 == 0) { size--; } buckets = new Node[size]; locks = new Lock[size]; for (int i = 0; i < size; i++) { locks[i] = new Lock(); } } //----------------------------------------------------------------------- /** * Determine the exact hash entry for the key. The hash algorithm * is rather simplistic, but it does the job: *

*

     *   He = |Hk mod n|
     * 
*

*

* He is the entry's hashCode, Hk is the key's hashCode, and n is * the number of buckets. *

*/ private final int getHash(Object key) { if (key == null) { return 0; } int hash = key.hashCode(); hash += ~(hash << 15); hash ^= (hash >>> 10); hash += (hash << 3); hash ^= (hash >>> 6); hash += ~(hash << 11); hash ^= (hash >>> 16); hash %= buckets.length; return (hash < 0) ? hash * -1 : hash; } /** * Gets the current size of the map. * The value is computed fresh each time the method is called. * * @return the current size */ public int size() { int cnt = 0; for (int i = 0; i < buckets.length; i++) { cnt += locks[i].size; } return cnt; } /** * Checks if the size is currently zero. * * @return true if empty */ public boolean isEmpty() { return (size() == 0); } /** * Gets the value associated with the key. * * @param key the key to retrieve * @return the associated value */ public V get(final Object key) { int hash = getHash(key); synchronized (locks[hash]) { Node n = buckets[hash]; while (n != null) { if (n.key == key || (n.key != null && n.key.equals(key))) { return n.value; } n = n.next; } } return null; } /** * Checks if the map contains the specified key. * * @param key the key to check * @return true if found */ public boolean containsKey(final Object key) { int hash = getHash(key); synchronized (locks[hash]) { Node n = buckets[hash]; while (n != null) { if (n.key == null || (n.key != null && n.key.equals(key))) { return true; } n = n.next; } } return false; } /** * Checks if the map contains the specified value. * * @param value the value to check * @return true if found */ public boolean containsValue(final Object value) { for (int i = 0; i < buckets.length; i++) { synchronized (locks[i]) { Node n = buckets[i]; while (n != null) { if (n.value == value || (n.value != null && n.value.equals(value))) { return true; } n = n.next; } } } return false; } //----------------------------------------------------------------------- /** * Puts a new key value mapping into the map. * * @param key the key to use * @param value the value to use * @return the previous mapping for the key */ public V put(final K key, final V value) { int hash = getHash(key); synchronized (locks[hash]) { Node n = buckets[hash]; if (n == null) { n = new Node(); n.key = key; n.value = value; buckets[hash] = n; locks[hash].size++; return null; } // Set n to the last node in the linked list. Check each key along the way // If the key is found, then change the value of that node and return // the old value. for (Node next = n; next != null; next = next.next) { n = next; if (n.key == key || (n.key != null && n.key.equals(key))) { V returnVal = n.value; n.value = value; return returnVal; } } // The key was not found in the current list of nodes, add it to the end // in a new node. Node newNode = new Node(); newNode.key = key; newNode.value = value; n.next = newNode; locks[hash].size++; } return null; } /** * Removes the specified key from the map. * * @param key the key to remove * @return the previous value at this key */ public V remove(Object key) { int hash = getHash(key); synchronized (locks[hash]) { Node n = buckets[hash]; Node prev = null; while (n != null) { if (n.key == key || (n.key != null && n.key.equals(key))) { // Remove this node from the linked list of nodes. if (null == prev) { // This node was the head, set the next node to be the new head. buckets[hash] = n.next; } else { // Set the next node of the previous node to be the node after this one. prev.next = n.next; } locks[hash].size--; return n.value; } prev = n; n = n.next; } } return null; } //----------------------------------------------------------------------- /** * Gets the key set. * * @return the key set */ public Set keySet() { return new KeySet(); } /** * Gets the values. * * @return the values */ public Collection values() { return new Values(); } /** * Gets the entry set. * * @return the entry set */ public Set> entrySet() { return new EntrySet(); } //----------------------------------------------------------------------- /** * Puts all the entries from the specified map into this map. * This operation is not atomic and may have undesired effects. * * @param map the map of entries to add */ public void putAll(Map map) { Iterator i = map.keySet().iterator(); while (i.hasNext()) { K key = (K) i.next(); put(key, (V) map.get(key)); } } /** * Clears the map of all entries. */ public void clear() { for (int i = 0; i < buckets.length; i++) { Lock lock = locks[i]; synchronized (lock) { buckets[i] = null; lock.size = 0; } } } /** * Compares this map to another, as per the Map specification. * * @param obj the object to compare to * @return true if equal */ public boolean equals(Object obj) { if (obj == this) { return true; } if (obj instanceof Map == false) { return false; } Map other = (Map) obj; return entrySet().equals(other.entrySet()); } /** * Gets the hash code, as per the Map specification. * * @return the hash code */ public int hashCode() { int hashCode = 0; for (int i = 0; i < buckets.length; i++) { synchronized (locks[i]) { Node n = buckets[i]; while (n != null) { hashCode += n.hashCode(); n = n.next; } } } return hashCode; } //----------------------------------------------------------------------- /** * The Map.Entry for the StaticBucketMap. */ private static final class Node implements Map.Entry, KeyValue { protected K key; protected V value; protected Node next; public K getKey() { return key; } public V getValue() { return value; } public int hashCode() { return ((key == null ? 0 : key.hashCode()) ^ (value == null ? 0 : value.hashCode())); } public boolean equals(Object obj) { if (obj == this) { return true; } if (obj instanceof Map.Entry == false) { return false; } Map.Entry e2 = (Map.Entry) obj; return ((key == null ? e2.getKey() == null : key.equals(e2.getKey())) && (value == null ? e2.getValue() == null : value.equals(e2.getValue()))); } public V setValue(V obj) { V retVal = value; value = obj; return retVal; } } /** * The lock object, which also includes a count of the nodes in this lock. */ private final static class Lock { public int size; } private class EntryIterator extends IteratorBase implements Iterator> { public Entry next() { return superNext(); } } //----------------------------------------------------------------------- private class IteratorBase { private ArrayList> current = new ArrayList>(); private int bucket; private Map.Entry last; public boolean hasNext() { if (current.size() > 0) return true; while (bucket < buckets.length) { synchronized (locks[bucket]) { Node n = buckets[bucket]; while (n != null) { current.add(n); n = n.next; } bucket++; if (current.size() > 0) return true; } } return false; } protected Map.Entry nextEntry() { if (!hasNext()) throw new NoSuchElementException(); last = current.remove(current.size() - 1); return last; } public Map.Entry superNext() { return nextEntry(); } public void remove() { if (last == null) throw new IllegalStateException(); StaticBucketMap.this.remove(last.getKey()); last = null; } } private class ValueIterator extends IteratorBase implements Iterator { public V next() { return nextEntry().getValue(); } } private class KeyIterator extends IteratorBase implements Iterator { public K next() { return nextEntry().getKey(); } } private class EntrySet extends AbstractSet> { public int size() { return StaticBucketMap.this.size(); } public void clear() { StaticBucketMap.this.clear(); } public Iterator> iterator() { return new EntryIterator(); } public boolean contains(Object obj) { Map.Entry entry = (Map.Entry) obj; int hash = getHash(entry.getKey()); synchronized (locks[hash]) { for (Node n = buckets[hash]; n != null; n = n.next) { if (n.equals(entry)) return true; } } return false; } public boolean remove(Object obj) { if (obj instanceof Map.Entry == false) { return false; } Map.Entry entry = (Map.Entry) obj; int hash = getHash(entry.getKey()); synchronized (locks[hash]) { for (Node n = buckets[hash]; n != null; n = n.next) { if (n.equals(entry)) { StaticBucketMap.this.remove(n.getKey()); return true; } } } return false; } } private class KeySet extends AbstractSet { public int size() { return StaticBucketMap.this.size(); } public void clear() { StaticBucketMap.this.clear(); } public Iterator iterator() { return new KeyIterator(); } public boolean contains(Object obj) { return StaticBucketMap.this.containsKey(obj); } public boolean remove(Object obj) { int hash = getHash(obj); synchronized (locks[hash]) { for (Node n = buckets[hash]; n != null; n = n.next) { Object k = n.getKey(); if ((k == obj) || ((k != null) && k.equals(obj))) { StaticBucketMap.this.remove(k); return true; } } } return false; } } private class Values extends AbstractCollection { public int size() { return StaticBucketMap.this.size(); } public void clear() { StaticBucketMap.this.clear(); } public Iterator iterator() { return new ValueIterator(); } } /** * Prevents any operations from occurring on this map while the * given {@link Runnable} executes. This method can be used, for * instance, to execute a bulk operation atomically: *

*

     *    staticBucketMapInstance.atomic(new Runnable() {
     *        public void run() {
     *            staticBucketMapInstance.putAll(map);
     *        }
     *    });
     *  
*

* It can also be used if you need a reliable iterator: *

*

     *    staticBucketMapInstance.atomic(new Runnable() {
     *        public void run() {
     *            Iterator iterator = staticBucketMapInstance.iterator();
     *            while (iterator.hasNext()) {
     *                foo(iterator.next();
     *            }
     *        }
     *    });
     *  
*

* Implementation note: This method requires a lot of time * and a ton of stack space. Essentially a recursive algorithm is used * to enter each bucket's monitor. If you have twenty thousand buckets * in your map, then the recursive method will be invoked twenty thousand * times. You have been warned. * * @param r the code to execute atomically */ public void atomic(Runnable r) { if (r == null) throw new NullPointerException(); atomic(r, 0); } private void atomic(Runnable r, int bucket) { if (bucket >= buckets.length) { r.run(); return; } synchronized (locks[bucket]) { atomic(r, bucket + 1); } } } collections-generic-4.01/src/java/org/apache/commons/collections15/map/package.html0000644000175000017500000000507210464140755030523 0ustar giovannigiovanni

This package contains implementations of the {@link java.util.Map Map}, {@link org.apache.commons.collections.IterableMap IterableMap}, {@link org.apache.commons.collections.OrderedMap OrderedMap} and {@link java.util.SortedMap SortedMap} interfaces. A Map provides a lookup from a key to a value. A number of implementations also support the new MapIterator interface that enables simple iteration of map keys and values.

The following implementations are provided:

  • CaseInsensitiveMap - map that compares keys in a case insensitive way
  • CompositeMap - map that combines multiple maps into a single view
  • HashedMap - general purpose HashMap replacement supporting MapIterator
  • IdentityMap - map that uses == for comparison instead of equals()
  • Flat3Map - designed for good performance at size 3 or less
  • LinkedMap - a hash map that maintains insertion order, supporting OrderedMapIterator
  • MultiKeyMap - map that provides special methods for using more than one key to access the value
  • ReferenceMap - allows the garbage collector to collect keys and values using equals() for comparison
  • ReferenceIdentityMap - allows the garbage collector to collect keys and values using == for comparison
  • SingletonMap - a fully featured map to hold one key-value pair
  • StaticBucketMap - internally synchronized and designed for thread-contentious environments

The following decorators are provided:

  • Unmodifiable - ensures the collection cannot be altered
  • Predicated - ensures that only elements that are valid according to a predicate can be added
  • Typed - ensures that only elements that are of a specific type can be added
  • Transformed - transforms each element added
  • FixedSize - ensures that the size of the map cannot change
  • Lazy - creates objects in the map on demand
  • ListOrdered - ensures that insertion order is retained
././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootcollections-generic-4.01/src/java/org/apache/commons/collections15/map/AbstractOrderedMapDecorator.javacollections-generic-4.01/src/java/org/apache/commons/collections15/map/AbstractOrderedMapDecorator.j0000644000175000017500000000566510464140761033773 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.map; import org.apache.commons.collections15.MapIterator; import org.apache.commons.collections15.OrderedMap; import org.apache.commons.collections15.OrderedMapIterator; /** * Provides a base decorator that enables additional functionality to be added * to an OrderedMap via decoration. *

* Methods are forwarded directly to the decorated map. *

* This implementation does not perform any special processing with the map views. * Instead it simply returns the set/collection from the wrapped map. This may be * undesirable, for example if you are trying to write a validating implementation * it would provide a loophole around the validation. * But, you might want that loophole, so this class is kept simple. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:32 $ * @since Commons Collections 3.0 */ public abstract class AbstractOrderedMapDecorator extends AbstractMapDecorator implements OrderedMap { /** * Constructor only used in deserialization, do not use otherwise. * * @since Commons Collections 3.1 */ protected AbstractOrderedMapDecorator() { super(); } /** * Constructor that wraps (not copies). * * @param map the map to decorate, must not be null * @throws IllegalArgumentException if the collection is null */ public AbstractOrderedMapDecorator(OrderedMap map) { super(map); } /** * Gets the map being decorated. * * @return the decorated map */ protected OrderedMap getOrderedMap() { return (OrderedMap) map; } //----------------------------------------------------------------------- public K firstKey() { return getOrderedMap().firstKey(); } public K lastKey() { return getOrderedMap().lastKey(); } public K nextKey(K key) { return getOrderedMap().nextKey(key); } public K previousKey(K key) { return getOrderedMap().previousKey(key); } public MapIterator mapIterator() { return getOrderedMap().mapIterator(); } public OrderedMapIterator orderedMapIterator() { return getOrderedMap().orderedMapIterator(); } } collections-generic-4.01/src/java/org/apache/commons/collections15/map/FixedSizeSortedMap.java0000644000175000017500000001257710464140756032627 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.map; import org.apache.commons.collections15.BoundedMap; import org.apache.commons.collections15.collection.UnmodifiableCollection; import org.apache.commons.collections15.set.UnmodifiableSet; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.*; /** * Decorates another SortedMap to fix the size blocking add/remove. *

* Any action that would change the size of the map is disallowed. * The put method is allowed to change the value associated with an existing * key however. *

* If trying to remove or clear the map, an UnsupportedOperationException is * thrown. If trying to put a new mapping into the map, an * IllegalArgumentException is thrown. This is because the put method can * succeed if the mapping's key already exists in the map, so the put method * is not always unsupported. *

* This class is Serializable from Commons Collections 3.1. * * @author Stephen Colebourne * @author Matt Hall, John Watkinson, Paul Jack * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:32 $ * @since Commons Collections 3.0 */ public class FixedSizeSortedMap extends AbstractSortedMapDecorator implements SortedMap, BoundedMap, Serializable { /** * Serialization version */ private static final long serialVersionUID = 3126019624511683653L; /** * Factory method to create a fixed size sorted map. * * @param map the map to decorate, must not be null * @throws IllegalArgumentException if map is null */ public static SortedMap decorate(SortedMap map) { return new FixedSizeSortedMap(map); } //----------------------------------------------------------------------- /** * Constructor that wraps (not copies). * * @param map the map to decorate, must not be null * @throws IllegalArgumentException if map is null */ protected FixedSizeSortedMap(SortedMap map) { super(map); } /** * Gets the map being decorated. * * @return the decorated map */ protected SortedMap getSortedMap() { return (SortedMap) map; } //----------------------------------------------------------------------- /** * Write the map out using a custom routine. */ private void writeObject(ObjectOutputStream out) throws IOException { out.defaultWriteObject(); out.writeObject(map); } /** * Read the map in using a custom routine. */ private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); map = (Map) in.readObject(); } //----------------------------------------------------------------------- public V put(K key, V value) { if (map.containsKey(key) == false) { throw new IllegalArgumentException("Cannot put new key/value pair - Map is fixed size"); } return map.put(key, value); } public void putAll(Map mapToCopy) { for (Iterator it = mapToCopy.keySet().iterator(); it.hasNext();) { if (mapToCopy.containsKey(it.next()) == false) { throw new IllegalArgumentException("Cannot put new key/value pair - Map is fixed size"); } } map.putAll(mapToCopy); } public void clear() { throw new UnsupportedOperationException("Map is fixed size"); } public V remove(Object key) { throw new UnsupportedOperationException("Map is fixed size"); } public Set> entrySet() { Set> set = map.entrySet(); return UnmodifiableSet.decorate(set); } public Set keySet() { Set set = map.keySet(); return UnmodifiableSet.decorate(set); } public Collection values() { Collection coll = map.values(); return UnmodifiableCollection.decorate(coll); } //----------------------------------------------------------------------- public SortedMap subMap(K fromKey, K toKey) { SortedMap map = getSortedMap().subMap(fromKey, toKey); return new FixedSizeSortedMap(map); } public SortedMap headMap(K toKey) { SortedMap map = getSortedMap().headMap(toKey); return new FixedSizeSortedMap(map); } public SortedMap tailMap(K fromKey) { SortedMap map = getSortedMap().tailMap(fromKey); return new FixedSizeSortedMap(map); } public boolean isFull() { return true; } public int maxSize() { return size(); } } collections-generic-4.01/src/java/org/apache/commons/collections15/map/CompositeMap.java0000644000175000017500000005561110464140755031511 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.map; import org.apache.commons.collections15.CollectionUtils; import org.apache.commons.collections15.collection.CompositeCollection; import org.apache.commons.collections15.set.CompositeSet; import java.util.Collection; import java.util.Iterator; import java.util.Map; import java.util.Set; /** * Decorates a map of other maps to provide a single unified view. *

* Changes made to this map will actually be made on the decorated map. * Add and remove operations require the use of a pluggable strategy. If no * strategy is provided then add and remove are unsupported. * * @author Matt Hall, John Watkinson, Brian McCallister * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:32 $ * @since Commons Collections 3.0 */ public class CompositeMap implements Map { /** * Array of all maps in the composite */ private Map[] composite; /** * Handle mutation operations */ private MapMutator mutator; /** * Create a new, empty, CompositeMap. */ public CompositeMap() { this(new Map[]{}, null); } /** * Create a new CompositeMap with two composited Map instances. * * @param one the first Map to be composited * @param two the second Map to be composited * @throws IllegalArgumentException if there is a key collision */ public CompositeMap(Map one, Map two) { this(new Map[]{one, two}, null); } /** * Create a new CompositeMap with two composited Map instances. * * @param one the first Map to be composited * @param two the second Map to be composited * @param mutator MapMutator to be used for mutation operations */ public CompositeMap(Map one, Map two, MapMutator mutator) { this(new Map[]{one, two}, mutator); } /** * Create a new CompositeMap which composites all of the Map instances in the * argument. It copies the argument array, it does not use it directly. * * @param composite the Maps to be composited * @throws IllegalArgumentException if there is a key collision */ public CompositeMap(Map[] composite) { this(composite, null); } /** * Create a new CompositeMap which composites all of the Map instances in the * argument. It copies the argument array, it does not use it directly. * * @param composite Maps to be composited * @param mutator MapMutator to be used for mutation operations */ public CompositeMap(Map[] composite, MapMutator mutator) { this.mutator = mutator; this.composite = new Map[0]; for (int i = composite.length - 1; i >= 0; --i) { this.addComposited(composite[i]); } } //----------------------------------------------------------------------- /** * Specify the MapMutator to be used by mutation operations. * * @param mutator the MapMutator to be used for mutation delegation */ public void setMutator(MapMutator mutator) { this.mutator = mutator; } /** * Add an additional Map to the composite. * * @param map the Map to be added to the composite * @throws IllegalArgumentException if there is a key collision and there is no * MapMutator set to handle it. */ public synchronized void addComposited(Map map) throws IllegalArgumentException { for (int i = composite.length - 1; i >= 0; --i) { Collection intersect = (Collection) CollectionUtils.intersection(this.composite[i].keySet(), map.keySet()); if (intersect.size() != 0) { if (this.mutator == null) { throw new IllegalArgumentException("Key collision adding Map to CompositeMap"); } else { this.mutator.resolveCollision(this, this.composite[i], map, intersect); } } } Map[] temp = new Map[this.composite.length + 1]; System.arraycopy(this.composite, 0, temp, 0, this.composite.length); temp[temp.length - 1] = map; this.composite = temp; } /** * Remove a Map from the composite. * * @param map the Map to be removed from the composite * @return The removed Map or null if map is not in the composite */ public synchronized Map removeComposited(Map map) { int size = this.composite.length; for (int i = 0; i < size; ++i) { if (this.composite[i].equals(map)) { Map[] temp = new Map[size - 1]; System.arraycopy(this.composite, 0, temp, 0, i); System.arraycopy(this.composite, i + 1, temp, i, size - i - 1); this.composite = temp; return map; } } return null; } //----------------------------------------------------------------------- /** * Calls clear() on all composited Maps. * * @throws UnsupportedOperationException if any of the composited Maps do not support clear() */ public void clear() { for (int i = this.composite.length - 1; i >= 0; --i) { this.composite[i].clear(); } } /** * Returns true if this map contains a mapping for the specified * key. More formally, returns true if and only if * this map contains at a mapping for a key k such that * (key==null ? k==null : key.equals(k)). (There can be * at most one such mapping.) * * @param key key whose presence in this map is to be tested. * @return true if this map contains a mapping for the specified * key. * @throws ClassCastException if the key is of an inappropriate type for * this map (optional). * @throws NullPointerException if the key is null and this map * does not not permit null keys (optional). */ public boolean containsKey(Object key) { for (int i = this.composite.length - 1; i >= 0; --i) { if (this.composite[i].containsKey(key)) { return true; } } return false; } /** * Returns true if this map maps one or more keys to the * specified value. More formally, returns true if and only if * this map contains at least one mapping to a value v such that * (value==null ? v==null : value.equals(v)). This operation * will probably require time linear in the map size for most * implementations of the Map interface. * * @param value value whose presence in this map is to be tested. * @return true if this map maps one or more keys to the * specified value. * @throws ClassCastException if the value is of an inappropriate type for * this map (optional). * @throws NullPointerException if the value is null and this map * does not not permit null values (optional). */ public boolean containsValue(Object value) { for (int i = this.composite.length - 1; i >= 0; --i) { if (this.composite[i].containsValue(value)) { return true; } } return false; } /** * Returns a set view of the mappings contained in this map. Each element * in the returned set is a Map.Entry. The set is backed by the * map, so changes to the map are reflected in the set, and vice-versa. * If the map is modified while an iteration over the set is in progress, * the results of the iteration are undefined. The set supports element * removal, which removes the corresponding mapping from the map, via the * Iterator.remove, Set.remove, removeAll, * retainAll and clear operations. It does not support * the add or addAll operations. *

* This implementation returns a CompositeSet which * composites the entry sets from all of the composited maps. * * @return a set view of the mappings contained in this map. * @see CompositeSet */ public Set entrySet() { CompositeSet> entries = new CompositeSet>(); for (int i = this.composite.length - 1; i >= 0; --i) { entries.addComposited(this.composite[i].entrySet()); } return entries; } /** * Returns the value to which this map maps the specified key. Returns * null if the map contains no mapping for this key. A return * value of null does not necessarily indicate that the * map contains no mapping for the key; it's also possible that the map * explicitly maps the key to null. The containsKey * operation may be used to distinguish these two cases. *

*

More formally, if this map contains a mapping from a key * k to a value v such that (key==null ? k==null : * key.equals(k)), then this method returns v; otherwise * it returns null. (There can be at most one such mapping.) * * @param key key whose associated value is to be returned. * @return the value to which this map maps the specified key, or * null if the map contains no mapping for this key. * @throws ClassCastException if the key is of an inappropriate type for * this map (optional). * @throws NullPointerException key is null and this map does not * not permit null keys (optional). * @see #containsKey(Object) */ public V get(Object key) { for (int i = this.composite.length - 1; i >= 0; --i) { if (this.composite[i].containsKey(key)) { return (V) this.composite[i].get(key); } } return null; } /** * Returns true if this map contains no key-value mappings. * * @return true if this map contains no key-value mappings. */ public boolean isEmpty() { for (int i = this.composite.length - 1; i >= 0; --i) { if (!this.composite[i].isEmpty()) { return false; } } return true; } /** * Returns a set view of the keys contained in this map. The set is * backed by the map, so changes to the map are reflected in the set, and * vice-versa. If the map is modified while an iteration over the set is * in progress, the results of the iteration are undefined. The set * supports element removal, which removes the corresponding mapping from * the map, via the Iterator.remove, Set.remove, * removeAll retainAll, and clear operations. * It does not support the add or addAll operations. *

* This implementation returns a CompositeSet which * composites the key sets from all of the composited maps. * * @return a set view of the keys contained in this map. */ public Set keySet() { CompositeSet keys = new CompositeSet(); for (int i = this.composite.length - 1; i >= 0; --i) { keys.addComposited(this.composite[i].keySet()); } return keys; } /** * Associates the specified value with the specified key in this map * (optional operation). If the map previously contained a mapping for * this key, the old value is replaced by the specified value. (A map * m is said to contain a mapping for a key k if and only * if {@link #containsKey(Object) m.containsKey(k)} would return * true.)) * * @param key key with which the specified value is to be associated. * @param value value to be associated with the specified key. * @return previous value associated with specified key, or null * if there was no mapping for key. A null return can * also indicate that the map previously associated null * with the specified key, if the implementation supports * null values. * @throws UnsupportedOperationException if no MapMutator has been specified * @throws ClassCastException if the class of the specified key or value * prevents it from being stored in this map. * @throws IllegalArgumentException if some aspect of this key or value * prevents it from being stored in this map. * @throws NullPointerException this map does not permit null * keys or values, and the specified key or value is * null. */ public V put(K key, V value) { if (this.mutator == null) { throw new UnsupportedOperationException("No mutator specified"); } return this.mutator.put(this, this.composite, key, value); } /** * Copies all of the mappings from the specified map to this map * (optional operation). The effect of this call is equivalent to that * of calling {@link #put(Object,Object) put(k, v)} on this map once * for each mapping from key k to value v in the * specified map. The behavior of this operation is unspecified if the * specified map is modified while the operation is in progress. * * @param map Mappings to be stored in this map. * @throws UnsupportedOperationException if the putAll method is * not supported by this map. * @throws ClassCastException if the class of a key or value in the * specified map prevents it from being stored in this map. * @throws IllegalArgumentException some aspect of a key or value in the * specified map prevents it from being stored in this map. * @throws NullPointerException the specified map is null, or if * this map does not permit null keys or values, and the * specified map contains null keys or values. */ public void putAll(Map map) { if (this.mutator == null) { throw new UnsupportedOperationException("No mutator specified"); } this.mutator.putAll(this, this.composite, map); } /** * Removes the mapping for this key from this map if it is present * (optional operation). More formally, if this map contains a mapping * from key k to value v such that * (key==null ? k==null : key.equals(k)), that mapping * is removed. (The map can contain at most one such mapping.) *

*

Returns the value to which the map previously associated the key, or * null if the map contained no mapping for this key. (A * null return can also indicate that the map previously * associated null with the specified key if the implementation * supports null values.) The map will not contain a mapping for * the specified key once the call returns. * * @param key key whose mapping is to be removed from the map. * @return previous value associated with specified key, or null * if there was no mapping for key. * @throws ClassCastException if the key is of an inappropriate type for * the composited map (optional). * @throws NullPointerException if the key is null and the composited map * does not not permit null keys (optional). * @throws UnsupportedOperationException if the remove method is * not supported by the composited map containing the key */ public V remove(Object key) { for (int i = this.composite.length - 1; i >= 0; --i) { if (this.composite[i].containsKey(key)) { return (V) this.composite[i].remove(key); } } return null; } /** * Returns the number of key-value mappings in this map. If the * map contains more than Integer.MAX_VALUE elements, returns * Integer.MAX_VALUE. * * @return the number of key-value mappings in this map. */ public int size() { int size = 0; for (int i = this.composite.length - 1; i >= 0; --i) { size += this.composite[i].size(); } return size; } /** * Returns a collection view of the values contained in this map. The * collection is backed by the map, so changes to the map are reflected in * the collection, and vice-versa. If the map is modified while an * iteration over the collection is in progress, the results of the * iteration are undefined. The collection supports element removal, * which removes the corresponding mapping from the map, via the * Iterator.remove, Collection.remove, * removeAll, retainAll and clear operations. * It does not support the add or addAll operations. * * @return a collection view of the values contained in this map. */ public Collection values() { CompositeCollection keys = new CompositeCollection(); for (int i = this.composite.length - 1; i >= 0; --i) { keys.addComposited(this.composite[i].values()); } return keys; } /** * Checks if this Map equals another as per the Map specification. * * @param obj the object to compare to * @return true if the maps are equal */ public boolean equals(Object obj) { if (obj instanceof Map) { Map map = (Map) obj; return (this.entrySet().equals(map.entrySet())); } return false; } /** * Gets a hash code for the Map as per the Map specification. */ public int hashCode() { int code = 0; for (Iterator i = this.entrySet().iterator(); i.hasNext();) { code += i.next().hashCode(); } return code; } /** * This interface allows definition for all of the indeterminate * mutators in a CompositeMap, as well as providing a hook for * callbacks on key collisions. */ public static interface MapMutator { /** * Called when adding a new Composited Map results in a * key collision. * * @param composite the CompositeMap with the collision * @param existing the Map already in the composite which contains the * offending key * @param added the Map being added * @param intersect the intersection of the keysets of the existing and added maps */ public void resolveCollision(CompositeMap composite, Map existing, Map added, Collection intersect); /** * Called when the CompositeMap.put() method is invoked. * * @param map the CompositeMap which is being modified * @param composited array of Maps in the CompositeMap being modified * @param key key with which the specified value is to be associated. * @param value value to be associated with the specified key. * @return previous value associated with specified key, or null * if there was no mapping for key. A null return can * also indicate that the map previously associated null * with the specified key, if the implementation supports * null values. * @throws UnsupportedOperationException if not defined * @throws ClassCastException if the class of the specified key or value * prevents it from being stored in this map. * @throws IllegalArgumentException if some aspect of this key or value * prevents it from being stored in this map. * @throws NullPointerException this map does not permit null * keys or values, and the specified key or value is * null. */ public V put(CompositeMap map, Map[] composited, K key, V value); /** * Called when the CompositeMap.putAll() method is invoked. * * @param map the CompositeMap which is being modified * @param composited array of Maps in the CompositeMap being modified * @param mapToAdd Mappings to be stored in this CompositeMap * @throws UnsupportedOperationException if not defined * @throws ClassCastException if the class of the specified key or value * prevents it from being stored in this map. * @throws IllegalArgumentException if some aspect of this key or value * prevents it from being stored in this map. * @throws NullPointerException this map does not permit null * keys or values, and the specified key or value is * null. */ public void putAll(CompositeMap map, Map[] composited, Map mapToAdd); } } collections-generic-4.01/src/java/org/apache/commons/collections15/map/UnmodifiableMap.java0000644000175000017500000001105110464140757032135 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.map; import org.apache.commons.collections15.IterableMap; import org.apache.commons.collections15.MapIterator; import org.apache.commons.collections15.Unmodifiable; import org.apache.commons.collections15.collection.UnmodifiableCollection; import org.apache.commons.collections15.iterators.EntrySetMapIterator; import org.apache.commons.collections15.iterators.UnmodifiableMapIterator; import org.apache.commons.collections15.set.UnmodifiableSet; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.Collection; import java.util.Map; import java.util.Set; /** * Decorates another Map to ensure it can't be altered. *

* This class is Serializable from Commons Collections 3.1. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:32 $ * @since Commons Collections 3.0 */ public final class UnmodifiableMap extends AbstractMapDecorator implements IterableMap, Unmodifiable, Serializable { /** * Serialization version */ private static final long serialVersionUID = 2737023427269031941L; /** * Factory method to create an unmodifiable map. * * @param map the map to decorate, must not be null * @throws IllegalArgumentException if map is null */ public static Map decorate(Map map) { if (map instanceof Unmodifiable) { return map; } return new UnmodifiableMap(map); } //----------------------------------------------------------------------- /** * Constructor that wraps (not copies). * * @param map the map to decorate, must not be null * @throws IllegalArgumentException if map is null */ private UnmodifiableMap(Map map) { super(map); } //----------------------------------------------------------------------- /** * Write the map out using a custom routine. * * @param out the output stream * @throws IOException * @since Commons Collections 3.1 */ private void writeObject(ObjectOutputStream out) throws IOException { out.defaultWriteObject(); out.writeObject(map); } /** * Read the map in using a custom routine. * * @param in the input stream * @throws IOException * @throws ClassNotFoundException * @since Commons Collections 3.1 */ private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); map = (Map) in.readObject(); } //----------------------------------------------------------------------- public void clear() { throw new UnsupportedOperationException(); } public V put(K key, V value) { throw new UnsupportedOperationException(); } public void putAll(Map mapToCopy) { throw new UnsupportedOperationException(); } public V remove(Object key) { throw new UnsupportedOperationException(); } public MapIterator mapIterator() { if (map instanceof IterableMap) { MapIterator it = ((IterableMap) map).mapIterator(); return UnmodifiableMapIterator.decorate(it); } else { MapIterator it = new EntrySetMapIterator(map); return UnmodifiableMapIterator.decorate(it); } } public Set> entrySet() { Set> set = super.entrySet(); return UnmodifiableEntrySet.decorate(set); } public Set keySet() { Set set = super.keySet(); return UnmodifiableSet.decorate(set); } public Collection values() { Collection coll = super.values(); return UnmodifiableCollection.decorate(coll); } } collections-generic-4.01/src/java/org/apache/commons/collections15/map/AbstractLinkedMap.java0000644000175000017500000004760110464140762032437 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.map; import org.apache.commons.collections15.*; import org.apache.commons.collections15.iterators.EmptyOrderedIterator; import org.apache.commons.collections15.iterators.EmptyOrderedMapIterator; import java.util.ConcurrentModificationException; import java.util.Iterator; import java.util.Map; import java.util.NoSuchElementException; /** * An abstract implementation of a hash-based map that links entries to create an * ordered map and which provides numerous points for subclasses to override. *

* This class implements all the features necessary for a subclass linked * hash-based map. Key-value entries are stored in instances of the * LinkEntry class which can be overridden and replaced. * The iterators can similarly be replaced, without the need to replace the KeySet, * EntrySet and Values view classes. *

* Overridable methods are provided to change the default hashing behaviour, and * to change how entries are added to and removed from the map. Hopefully, all you * need for unusual subclasses is here. *

* This implementation maintains order by original insertion, but subclasses * may work differently. The OrderedMap interface is implemented * to provide access to bidirectional iteration and extra convenience methods. *

* The orderedMapIterator() method provides direct access to a * bidirectional iterator. The iterators from the other views can also be cast * to OrderedIterator if required. *

* All the available iterators can be reset back to the start by casting to * ResettableIterator and calling reset(). *

* The implementation is also designed to be subclassed, with lots of useful * methods exposed. * * @author java util LinkedHashMap * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:32 $ * @since Commons Collections 3.0 */ public class AbstractLinkedMap extends AbstractHashedMap implements OrderedMap { /** * Header in the linked list */ protected transient LinkEntry header; /** * Constructor only used in deserialization, do not use otherwise. */ protected AbstractLinkedMap() { super(); } /** * Constructor which performs no validation on the passed in parameters. * * @param initialCapacity the initial capacity, must be a power of two * @param loadFactor the load factor, must be > 0.0f and generally < 1.0f * @param threshold the threshold, must be sensible */ protected AbstractLinkedMap(int initialCapacity, float loadFactor, int threshold) { super(initialCapacity, loadFactor, threshold); } /** * Constructs a new, empty map with the specified initial capacity. * * @param initialCapacity the initial capacity * @throws IllegalArgumentException if the initial capacity is less than one */ protected AbstractLinkedMap(int initialCapacity) { super(initialCapacity); } /** * Constructs a new, empty map with the specified initial capacity and * load factor. * * @param initialCapacity the initial capacity * @param loadFactor the load factor * @throws IllegalArgumentException if the initial capacity is less than one * @throws IllegalArgumentException if the load factor is less than zero */ protected AbstractLinkedMap(int initialCapacity, float loadFactor) { super(initialCapacity, loadFactor); } /** * Constructor copying elements from another map. * * @param map the map to copy * @throws NullPointerException if the map is null */ protected AbstractLinkedMap(Map map) { super(map); } /** * Initialise this subclass during construction. */ protected void init() { header = new LinkEntry(null, -1, null, null); header.before = header.after = header; } //----------------------------------------------------------------------- /** * Checks whether the map contains the specified value. * * @param value the value to search for * @return true if the map contains the value */ public boolean containsValue(Object value) { // override uses faster iterator if (value == null) { for (LinkEntry entry = header.after; entry != header; entry = entry.after) { if (entry.getValue() == null) { return true; } } } else { for (LinkEntry entry = header.after; entry != header; entry = entry.after) { if (isEqualValue(value, entry.getValue())) { return true; } } } return false; } /** * Clears the map, resetting the size to zero and nullifying references * to avoid garbage collection issues. */ public void clear() { // override to reset the linked list super.clear(); header.before = header.after = header; } //----------------------------------------------------------------------- /** * Gets the first key in the map, which is the most recently inserted. * * @return the most recently inserted key */ public K firstKey() { if (size == 0) { throw new NoSuchElementException("Map is empty"); } return header.after.getKey(); } /** * Gets the last key in the map, which is the first inserted. * * @return the eldest key */ public K lastKey() { if (size == 0) { throw new NoSuchElementException("Map is empty"); } return header.before.getKey(); } /** * Gets the next key in sequence. * * @param key the key to get after * @return the next key */ public K nextKey(K key) { LinkEntry entry = (LinkEntry) getEntry(key); return (entry == null || entry.after == header ? null : entry.after.getKey()); } /** * Gets the previous key in sequence. * * @param key the key to get before * @return the previous key */ public K previousKey(K key) { LinkEntry entry = (LinkEntry) getEntry(key); return (entry == null || entry.before == header ? null : entry.before.getKey()); } //----------------------------------------------------------------------- /** * Gets the key at the specified index. * * @param index the index to retrieve * @return the key at the specified index * @throws IndexOutOfBoundsException if the index is invalid */ protected LinkEntry getEntry(int index) { if (index < 0) { throw new IndexOutOfBoundsException("Index " + index + " is less than zero"); } if (index >= size) { throw new IndexOutOfBoundsException("Index " + index + " is invalid for size " + size); } LinkEntry entry; if (index < (size / 2)) { // Search forwards entry = header.after; for (int currentIndex = 0; currentIndex < index; currentIndex++) { entry = entry.after; } } else { // Search backwards entry = header; for (int currentIndex = size; currentIndex > index; currentIndex--) { entry = entry.before; } } return entry; } /** * Adds an entry into this map, maintaining insertion order. *

* This implementation adds the entry to the data storage table and * to the end of the linked list. * * @param entry the entry to add * @param hashIndex the index into the data array to store at */ protected void addEntry(HashEntry entry, int hashIndex) { LinkEntry link = (LinkEntry) entry; link.after = header; link.before = header.before; header.before.after = link; header.before = link; data[hashIndex] = entry; } /** * Creates an entry to store the data. *

* This implementation creates a new LinkEntry instance. * * @param next the next entry in sequence * @param hashCode the hash code to use * @param key the key to store * @param value the value to store * @return the newly created entry */ protected HashEntry createEntry(HashEntry next, int hashCode, K key, V value) { return new LinkEntry(next, hashCode, key, value); } /** * Removes an entry from the map and the linked list. *

* This implementation removes the entry from the linked list chain, then * calls the superclass implementation. * * @param entry the entry to remove * @param hashIndex the index into the data structure * @param previous the previous entry in the chain */ protected void removeEntry(HashEntry entry, int hashIndex, HashEntry previous) { LinkEntry link = (LinkEntry) entry; link.before.after = link.after; link.after.before = link.before; link.after = null; link.before = null; super.removeEntry(entry, hashIndex, previous); } //----------------------------------------------------------------------- /** * Gets the before field from a LinkEntry. * Used in subclasses that have no visibility of the field. * * @param entry the entry to query, must not be null * @return the before field of the entry * @throws NullPointerException if the entry is null * @since Commons Collections 3.1 */ protected LinkEntry entryBefore(LinkEntry entry) { return entry.before; } /** * Gets the after field from a LinkEntry. * Used in subclasses that have no visibility of the field. * * @param entry the entry to query, must not be null * @return the after field of the entry * @throws NullPointerException if the entry is null * @since Commons Collections 3.1 */ protected LinkEntry entryAfter(LinkEntry entry) { return entry.after; } //----------------------------------------------------------------------- /** * Gets an iterator over the map. * Changes made to the iterator affect this map. *

* A MapIterator returns the keys in the map. It also provides convenient * methods to get the key and value, and set the value. * It avoids the need to create an entrySet/keySet/values object. * * @return the map iterator */ public MapIterator mapIterator() { if (size == 0) { return EmptyOrderedMapIterator.INSTANCE; } return new LinkMapIterator(this); } /** * Gets a bidirectional iterator over the map. * Changes made to the iterator affect this map. *

* A MapIterator returns the keys in the map. It also provides convenient * methods to get the key and value, and set the value. * It avoids the need to create an entrySet/keySet/values object. * * @return the map iterator */ public OrderedMapIterator orderedMapIterator() { if (size == 0) { return EmptyOrderedMapIterator.INSTANCE; } return new LinkMapIterator(this); } /** * MapIterator implementation. */ protected static class LinkMapIterator extends LinkIterator implements OrderedMapIterator, OrderedIterator, ResettableIterator { protected LinkMapIterator(AbstractLinkedMap parent) { super(parent); } public K next() { return super.nextEntry().getKey(); } public K previous() { return super.previousEntry().getKey(); } public K getKey() { HashEntry current = currentEntry(); if (current == null) { throw new IllegalStateException(AbstractHashedMap.GETKEY_INVALID); } return current.getKey(); } public V getValue() { HashEntry current = currentEntry(); if (current == null) { throw new IllegalStateException(AbstractHashedMap.GETVALUE_INVALID); } return current.getValue(); } public V setValue(V value) { HashEntry current = currentEntry(); if (current == null) { throw new IllegalStateException(AbstractHashedMap.SETVALUE_INVALID); } return current.setValue(value); } } //----------------------------------------------------------------------- /** * Creates an entry set iterator. * Subclasses can override this to return iterators with different properties. * * @return the entrySet iterator */ protected Iterator> createEntrySetIterator() { if (size() == 0) { return EmptyOrderedIterator.INSTANCE; } return new EntrySetIterator(this); } /** * EntrySet iterator. */ protected static class EntrySetIterator extends LinkIterator implements OrderedIterator>, ResettableIterator> { protected EntrySetIterator(AbstractLinkedMap parent) { super(parent); } public Map.Entry next() { return super.nextEntry(); } public Map.Entry previous() { return super.previousEntry(); } } //----------------------------------------------------------------------- /** * Creates a key set iterator. * Subclasses can override this to return iterators with different properties. * * @return the keySet iterator */ protected Iterator createKeySetIterator() { if (size() == 0) { return EmptyOrderedIterator.INSTANCE; } return new KeySetIterator(this); } /** * KeySet iterator. */ protected static class KeySetIterator extends LinkIterator implements OrderedIterator, ResettableIterator { protected KeySetIterator(AbstractLinkedMap parent) { super(parent); } public K next() { return super.nextEntry().getKey(); } public K previous() { return super.previousEntry().getKey(); } } //----------------------------------------------------------------------- /** * Creates a values iterator. * Subclasses can override this to return iterators with different properties. * * @return the values iterator */ protected Iterator createValuesIterator() { if (size() == 0) { return EmptyOrderedIterator.INSTANCE; } return new ValuesIterator(this); } /** * Values iterator. */ protected static class ValuesIterator extends LinkIterator implements OrderedIterator, ResettableIterator { protected ValuesIterator(AbstractLinkedMap parent) { super(parent); } public V next() { return super.nextEntry().getValue(); } public V previous() { return super.previousEntry().getValue(); } } //----------------------------------------------------------------------- /** * LinkEntry that stores the data. *

* If you subclass AbstractLinkedMap but not LinkEntry * then you will not be able to access the protected fields. * The entryXxx() methods on AbstractLinkedMap exist * to provide the necessary access. */ protected static class LinkEntry extends HashEntry { /** * The entry before this one in the order */ protected LinkEntry before; /** * The entry after this one in the order */ protected LinkEntry after; /** * Constructs a new entry. * * @param next the next entry in the hash bucket sequence * @param hashCode the hash code * @param key the key * @param value the value */ protected LinkEntry(HashEntry next, int hashCode, K key, V value) { super(next, hashCode, key, value); } } /** * Base Iterator that iterates in link order. */ protected static abstract class LinkIterator { /** * The parent map */ protected final AbstractLinkedMap parent; /** * The current (last returned) entry */ protected LinkEntry last; /** * The next entry */ protected LinkEntry next; /** * The modification count expected */ protected int expectedModCount; protected LinkIterator(AbstractLinkedMap parent) { super(); this.parent = parent; this.next = parent.header.after; this.expectedModCount = parent.modCount; } public boolean hasNext() { return (next != parent.header); } public boolean hasPrevious() { return (next.before != parent.header); } protected LinkEntry nextEntry() { if (parent.modCount != expectedModCount) { throw new ConcurrentModificationException(); } if (next == parent.header) { throw new NoSuchElementException(AbstractHashedMap.NO_NEXT_ENTRY); } last = next; next = next.after; return last; } protected LinkEntry previousEntry() { if (parent.modCount != expectedModCount) { throw new ConcurrentModificationException(); } LinkEntry previous = next.before; if (previous == parent.header) { throw new NoSuchElementException(AbstractHashedMap.NO_PREVIOUS_ENTRY); } next = previous; last = previous; return last; } protected LinkEntry currentEntry() { return last; } public void remove() { if (last == null) { throw new IllegalStateException(AbstractHashedMap.REMOVE_INVALID); } if (parent.modCount != expectedModCount) { throw new ConcurrentModificationException(); } parent.remove(last.getKey()); last = null; expectedModCount = parent.modCount; } public void reset() { last = null; next = parent.header.after; } public String toString() { if (last != null) { return "Iterator[" + last.getKey() + "=" + last.getValue() + "]"; } else { return "Iterator[]"; } } } } collections-generic-4.01/src/java/org/apache/commons/collections15/map/ListOrderedMap.java0000644000175000017500000004343110464140763031763 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.map; import org.apache.commons.collections15.MapIterator; import org.apache.commons.collections15.OrderedMap; import org.apache.commons.collections15.OrderedMapIterator; import org.apache.commons.collections15.ResettableIterator; import org.apache.commons.collections15.iterators.AbstractIteratorDecorator; import org.apache.commons.collections15.keyvalue.AbstractMapEntry; import org.apache.commons.collections15.list.UnmodifiableList; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.*; /** * Decorates a Map to ensure that the order of addition is retained * using a List to maintain order. *

* The order will be used via the iterators and toArray methods on the views. * The order is also returned by the MapIterator. * The orderedMapIterator() method accesses an iterator that can * iterate both forwards and backwards through the map. * In addition, non-interface methods are provided to access the map by index. *

* If an object is added to the Map for a second time, it will remain in the * original position in the iteration. *

* This class is Serializable from Commons Collections 3.1. * * @author Henri Yandell * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:32 $ * @since Commons Collections 3.0 */ public class ListOrderedMap extends AbstractMapDecorator implements OrderedMap, Serializable { /** * Serialization version */ private static final long serialVersionUID = 2728177751851003750L; /** * Internal list to hold the sequence of objects */ protected final List insertOrder = new ArrayList(); /** * Factory method to create an ordered map. *

* An ArrayList is used to retain order. * * @param map the map to decorate, must not be null * @throws IllegalArgumentException if map is null */ public static OrderedMap decorate(Map map) { return new ListOrderedMap(map); } //----------------------------------------------------------------------- /** * Constructs a new empty ListOrderedMap that decorates * a HashMap. * * @since Commons Collections 3.1 */ public ListOrderedMap() { this(new HashMap()); } /** * Constructor that wraps (not copies). * * @param map the map to decorate, must not be null * @throws IllegalArgumentException if map is null */ protected ListOrderedMap(Map map) { super(map); insertOrder.addAll(getMap().keySet()); } //----------------------------------------------------------------------- /** * Write the map out using a custom routine. * * @param out the output stream * @throws IOException * @since Commons Collections 3.1 */ private void writeObject(ObjectOutputStream out) throws IOException { out.defaultWriteObject(); out.writeObject(map); } /** * Read the map in using a custom routine. * * @param in the input stream * @throws IOException * @throws ClassNotFoundException * @since Commons Collections 3.1 */ private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); map = (Map) in.readObject(); } // Implement OrderedMap //----------------------------------------------------------------------- public MapIterator mapIterator() { return orderedMapIterator(); } public OrderedMapIterator orderedMapIterator() { return new ListOrderedMapIterator(this); } /** * Gets the first key in this map by insert order. * * @return the first key currently in this map * @throws NoSuchElementException if this map is empty */ public K firstKey() { if (size() == 0) { throw new NoSuchElementException("Map is empty"); } return insertOrder.get(0); } /** * Gets the last key in this map by insert order. * * @return the last key currently in this map * @throws NoSuchElementException if this map is empty */ public K lastKey() { if (size() == 0) { throw new NoSuchElementException("Map is empty"); } return insertOrder.get(size() - 1); } /** * Gets the next key to the one specified using insert order. * This method performs a list search to find the key and is O(n). * * @param key the key to find previous for * @return the next key, null if no match or at start */ public K nextKey(K key) { int index = insertOrder.indexOf(key); if (index >= 0 && index < size() - 1) { return insertOrder.get(index + 1); } return null; } /** * Gets the previous key to the one specified using insert order. * This method performs a list search to find the key and is O(n). * * @param key the key to find previous for * @return the previous key, null if no match or at start */ public K previousKey(K key) { int index = insertOrder.indexOf(key); if (index > 0) { return insertOrder.get(index - 1); } return null; } //----------------------------------------------------------------------- public V put(K key, V value) { if (getMap().containsKey(key)) { // re-adding doesn't change order return getMap().put(key, value); } else { // first add, so add to both map and list V result = getMap().put(key, value); insertOrder.add(key); return result; } } public void putAll(Map map) { for (Iterator it = map.entrySet().iterator(); it.hasNext();) { Map.Entry entry = (Map.Entry) it.next(); put((K) entry.getKey(), (V) entry.getValue()); } } public V remove(Object key) { V result = getMap().remove(key); insertOrder.remove(key); return result; } public void clear() { getMap().clear(); insertOrder.clear(); } //----------------------------------------------------------------------- public Set keySet() { return new KeySetView(this); } public Collection values() { return new ValuesView(this); } public Set> entrySet() { return new EntrySetView(this, this.insertOrder); } //----------------------------------------------------------------------- /** * Returns the Map as a string. * * @return the Map as a String */ public String toString() { if (isEmpty()) { return "{}"; } StringBuffer buf = new StringBuffer(); buf.append('{'); boolean first = true; Iterator it = entrySet().iterator(); while (it.hasNext()) { Map.Entry entry = (Map.Entry) it.next(); Object key = entry.getKey(); Object value = entry.getValue(); if (first) { first = false; } else { buf.append(", "); } buf.append(key == this ? "(this Map)" : key); buf.append('='); buf.append(value == this ? "(this Map)" : value); } buf.append('}'); return buf.toString(); } //----------------------------------------------------------------------- /** * Gets the key at the specified index. * * @param index the index to retrieve * @return the key at the specified index * @throws IndexOutOfBoundsException if the index is invalid */ public K get(int index) { return insertOrder.get(index); } /** * Gets the value at the specified index. * * @param index the index to retrieve * @return the key at the specified index * @throws IndexOutOfBoundsException if the index is invalid */ public V getValue(int index) { return get(insertOrder.get(index)); } /** * Gets the index of the specified key. * * @param key the key to find the index of * @return the index, or -1 if not found */ public int indexOf(Object key) { return insertOrder.indexOf(key); } /** * Removes the element at the specified index. * * @param index the index of the object to remove * @return the previous value corresponding the key, * or null if none existed * @throws IndexOutOfBoundsException if the index is invalid */ public Object remove(int index) { return remove(get(index)); } /** * Gets an unmodifiable List view of the keys which changes as the map changes. *

* The returned list is unmodifiable because changes to the values of * the list (using {@link java.util.ListIterator#set(Object)}) will * effectively remove the value from the list and reinsert that value at * the end of the list, which is an unexpected side effect of changing the * value of a list. This occurs because changing the key, changes when the * mapping is added to the map and thus where it appears in the list. *

* An alternative to this method is to use {@link #keySet()}. * * @return The ordered list of keys. * @see #keySet() */ public List asList() { return UnmodifiableList.decorate(insertOrder); } //----------------------------------------------------------------------- static class ValuesView extends AbstractCollection { private final ListOrderedMap parent; ValuesView(ListOrderedMap parent) { super(); this.parent = parent; } public int size() { return this.parent.size(); } public boolean contains(Object value) { return this.parent.containsValue(value); } public void clear() { this.parent.clear(); } public Iterator iterator() { return new AbstractIteratorDecorator(parent.entrySet().iterator()) { public Object next() { return ((Map.Entry) iterator.next()).getValue(); } }; } } //----------------------------------------------------------------------- static class KeySetView extends AbstractSet { private final ListOrderedMap parent; KeySetView(ListOrderedMap parent) { super(); this.parent = parent; } public int size() { return this.parent.size(); } public boolean contains(Object value) { return this.parent.containsKey(value); } public void clear() { this.parent.clear(); } public Iterator iterator() { final Iterator> entryIterator = parent.entrySet().iterator(); return new Iterator() { public K next() { return entryIterator.next().getKey(); } public boolean hasNext() { return entryIterator.hasNext(); } public void remove() { entryIterator.remove(); } }; } } //----------------------------------------------------------------------- static class EntrySetView extends AbstractSet> { private final ListOrderedMap parent; private final List insertOrder; private Set> entrySet; public EntrySetView(ListOrderedMap parent, List insertOrder) { super(); this.parent = parent; this.insertOrder = insertOrder; } private Set> getEntrySet() { if (entrySet == null) { entrySet = parent.getMap().entrySet(); } return entrySet; } public int size() { return this.parent.size(); } public boolean isEmpty() { return this.parent.isEmpty(); } public boolean contains(Object obj) { return getEntrySet().contains(obj); } public boolean containsAll(Collection coll) { return getEntrySet().containsAll(coll); } public boolean remove(Object obj) { if (obj instanceof Map.Entry == false) { return false; } if (getEntrySet().contains(obj)) { Object key = ((Map.Entry) obj).getKey(); parent.remove(key); return true; } return false; } public void clear() { this.parent.clear(); } public boolean equals(Object obj) { if (obj == this) { return true; } return getEntrySet().equals(obj); } public int hashCode() { return getEntrySet().hashCode(); } public String toString() { return getEntrySet().toString(); } public Iterator> iterator() { return new ListOrderedIterator(parent, insertOrder); } } //----------------------------------------------------------------------- static class ListOrderedIterator implements Iterator> { private final ListOrderedMap parent; private K last = null; private Iterator listIterator; ListOrderedIterator(ListOrderedMap parent, List insertOrder) { listIterator = insertOrder.iterator(); this.parent = parent; } public Map.Entry next() { last = listIterator.next(); return new ListOrderedMapEntry(parent, last); } public void remove() { listIterator.remove(); parent.getMap().remove(last); } public boolean hasNext() { return listIterator.hasNext(); } } //----------------------------------------------------------------------- static class ListOrderedMapEntry extends AbstractMapEntry { private final ListOrderedMap parent; ListOrderedMapEntry(ListOrderedMap parent, K key) { super(key, null); this.parent = parent; } public V getValue() { return parent.get(key); } public V setValue(V value) { return parent.getMap().put(key, value); } } //----------------------------------------------------------------------- static class ListOrderedMapIterator implements OrderedMapIterator, ResettableIterator { private final ListOrderedMap parent; private ListIterator iterator; private K last = null; private boolean readable = false; ListOrderedMapIterator(ListOrderedMap parent) { super(); this.parent = parent; this.iterator = parent.insertOrder.listIterator(); } public boolean hasNext() { return iterator.hasNext(); } public K next() { last = iterator.next(); readable = true; return last; } public boolean hasPrevious() { return iterator.hasPrevious(); } public K previous() { last = iterator.previous(); readable = true; return last; } public void remove() { if (readable == false) { throw new IllegalStateException(AbstractHashedMap.REMOVE_INVALID); } iterator.remove(); parent.map.remove(last); readable = false; } public K getKey() { if (readable == false) { throw new IllegalStateException(AbstractHashedMap.GETKEY_INVALID); } return last; } public V getValue() { if (readable == false) { throw new IllegalStateException(AbstractHashedMap.GETVALUE_INVALID); } return parent.get(last); } public V setValue(V value) { if (readable == false) { throw new IllegalStateException(AbstractHashedMap.SETVALUE_INVALID); } return parent.map.put(last, value); } public void reset() { iterator = parent.insertOrder.listIterator(); last = null; readable = false; } public String toString() { if (readable == true) { return "Iterator[" + getKey() + "=" + getValue() + "]"; } else { return "Iterator[]"; } } } } collections-generic-4.01/src/java/org/apache/commons/collections15/FactoryUtils.java0000644000175000017500000001237210464140754030760 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2002-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15; import org.apache.commons.collections15.functors.ConstantFactory; import org.apache.commons.collections15.functors.ExceptionFactory; import org.apache.commons.collections15.functors.InstantiateFactory; import org.apache.commons.collections15.functors.PrototypeFactory; /** * FactoryUtils provides reference implementations and utilities * for the Factory functor interface. The supplied factories are: *

    *
  • Prototype - clones a specified object *
  • Reflection - creates objects using reflection *
  • Constant - always returns the same object *
  • Null - always returns null *
  • Exception - always throws an exception *
* All the supplied factories are Serializable. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:19 $ * @since Commons Collections 3.0 */ public class FactoryUtils { /** * This class is not normally instantiated. */ public FactoryUtils() { super(); } /** * Gets a Factory that always throws an exception. * This could be useful during testing as a placeholder. * * @return the factory * @see org.apache.commons.collections15.functors.ExceptionFactory */ public static Factory exceptionFactory() { return ExceptionFactory.INSTANCE; } /** * Gets a Factory that will return null each time the factory is used. * This could be useful during testing as a placeholder. * * @return the factory * @see org.apache.commons.collections15.functors.ConstantFactory */ public static Factory nullFactory() { return ConstantFactory.NULL_INSTANCE; } /** * Creates a Factory that will return the same object each time the factory * is used. No check is made that the object is immutable. In general, only * immutable objects should use the constant factory. Mutable objects should * use the prototype factory. * * @param constantToReturn the constant object to return each time in the factory * @return the constant factory. * @see org.apache.commons.collections15.functors.ConstantFactory */ public static Factory constantFactory(T constantToReturn) { return ConstantFactory.getInstance(constantToReturn); } /** * Creates a Factory that will return a clone of the same prototype object * each time the factory is used. The prototype will be cloned using one of these * techniques (in order): *
    *
  • public clone method *
  • public copy constructor *
  • serialization clone *
      * * @param prototype the object to clone each time in the factory * @return the prototype factory * @throws IllegalArgumentException if the prototype is null * @throws IllegalArgumentException if the prototype cannot be cloned * @see org.apache.commons.collections15.functors.PrototypeFactory */ public static Factory prototypeFactory(T prototype) { return PrototypeFactory.getInstance(prototype); } /** * Creates a Factory that can create objects of a specific type using * a no-args constructor. * * @param classToInstantiate the Class to instantiate each time in the factory * @return the reflection factory * @throws IllegalArgumentException if the classToInstantiate is null * @see org.apache.commons.collections15.functors.InstantiateFactory */ public static Factory instantiateFactory(Class classToInstantiate) { return InstantiateFactory.getInstance(classToInstantiate, null, null); } /** * Creates a Factory that can create objects of a specific type using * the arguments specified to this method. * * @param classToInstantiate the Class to instantiate each time in the factory * @param paramTypes parameter types for the constructor, can be null * @param args the arguments to pass to the constructor, can be null * @return the reflection factory * @throws IllegalArgumentException if the classToInstantiate is null * @throws IllegalArgumentException if the paramTypes and args don't match * @throws IllegalArgumentException if the constructor doesn't exist * @see org.apache.commons.collections15.functors.InstantiateFactory */ public static Factory instantiateFactory(Class classToInstantiate, Class[] paramTypes, Object[] args) { return InstantiateFactory.getInstance(classToInstantiate, paramTypes, args); } } collections-generic-4.01/src/java/org/apache/commons/collections15/EnumerationUtils.java0000644000175000017500000000341310464140760031630 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15; import org.apache.commons.collections15.iterators.EnumerationIterator; import java.util.Enumeration; import java.util.List; /** * Provides utility methods for {@link Enumeration} instances. * * @author Matt Hall, John Watkinson, Gary Gregory * @version $Id: EnumerationUtils.java,v 1.1 2005/10/11 17:05:19 pents90 Exp $ * @since Commons Collections 3.0 */ public class EnumerationUtils { /** * EnumerationUtils is not normally instantiated. */ public EnumerationUtils() { // no init. } /** * Creates a list based on an enumeration. *

      *

      As the enumeration is traversed, an ArrayList of its values is * created. The new list is returned.

      * * @param enumeration the enumeration to traverse, which should not be null. * @throws NullPointerException if the enumeration parameter is null. */ public static List toList(Enumeration enumeration) { return IteratorUtils.toList(new EnumerationIterator(enumeration)); } } collections-generic-4.01/src/java/org/apache/commons/collections15/BoundedCollection.java0000644000175000017500000000317410464140763031724 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2002-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15; import java.util.Collection; /** * Defines a collection that is bounded in size. *

      * The size of the collection can vary, but it can never exceed a preset * maximum number of elements. This interface allows the querying of details * associated with the maximum number of elements. * * @author Matt Hall, John Watkinson, Herve Quiroz * @author Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:19 $ * @see CollectionUtils#isFull * @see CollectionUtils#maxSize * @since Commons Collections 3.0 */ public interface BoundedCollection extends Collection { /** * Returns true if this collection is full and no new elements can be added. * * @return true if the collection is full */ boolean isFull(); /** * Gets the maximum size of the collection (the bound). * * @return the maximum number of elements the collection can hold */ int maxSize(); } collections-generic-4.01/src/java/org/apache/commons/collections15/CollectionUtils.java0000644000175000017500000012515310464140764031447 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15; import org.apache.commons.collections15.collection.*; import java.lang.reflect.Array; import java.util.*; /** * Provides utility methods and decorators for {@link Collection} instances. * * @author Rodney Waldhoff * @author Paul Jack * @author Stephen Colebourne * @author Steve Downey * @author Herve Quiroz * @author Peter KoBek * @author Matthew Hawthorne * @author Janek Bogucki * @author Phil Steitz * @author Steven Melzer * @author Matt Hall, John Watkinson, Jon Schewe * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:19 $ * @since Commons Collections 1.0 */ public class CollectionUtils { /** * Constant to avoid repeated object creation */ private static Integer INTEGER_ONE = new Integer(1); /** * An empty unmodifiable collection. * The JDK provides empty Set and List implementations which could be used for * this purpose. However they could be cast to Set or List which might be * undesirable. This implementation only implements Collection. */ public static final Collection EMPTY_COLLECTION = UnmodifiableCollection.decorate(new ArrayList()); /** * CollectionUtils should not normally be instantiated. */ public CollectionUtils() { } /** * Returns a {@link Collection} containing the union * of the given {@link Collection}s. *

      * The cardinality of each element in the returned {@link Collection} * will be equal to the maximum of the cardinality of that element * in the two given {@link Collection}s. * * @param a the first collection, must not be null * @param b the second collection, must not be null * @return the union of the two collections15 * @see Collection#addAll */ public static Collection union(final Collection a, final Collection b) { ArrayList list = new ArrayList(); Map mapa = getCardinalityMap(a); Map mapb = getCardinalityMap(b); Set elts = new HashSet(a); elts.addAll(b); Iterator it = elts.iterator(); while (it.hasNext()) { E obj = it.next(); for (int i = 0, m = Math.max(getFreq(obj, mapa), getFreq(obj, mapb)); i < m; i++) { list.add(obj); } } return list; } /** * Returns a {@link Collection} containing the intersection * of the given {@link Collection}s. *

      * The cardinality of each element in the returned {@link Collection} * will be equal to the minimum of the cardinality of that element * in the two given {@link Collection}s. * * @param a the first collection, must not be null * @param b the second collection, must not be null * @return the intersection of the two collections15 * @see Collection#retainAll * @see #containsAny */ public static Collection intersection(final Collection a, final Collection b) { ArrayList list = new ArrayList(); Map mapa = getCardinalityMap(a); Map mapb = getCardinalityMap(b); Set elts = new HashSet(a); elts.addAll(b); Iterator it = elts.iterator(); while (it.hasNext()) { E obj = it.next(); for (int i = 0, m = Math.min(getFreq(obj, mapa), getFreq(obj, mapb)); i < m; i++) { list.add(obj); } } return list; } /** * Returns a {@link Collection} containing the exclusive disjunction * (symmetric difference) of the given {@link Collection}s. *

      * The cardinality of each element e in the returned {@link Collection} * will be equal to * max(cardinality(e,a),cardinality(e,b)) - min(cardinality(e,a),cardinality(e,b)). *

      * This is equivalent to * {@link #subtract subtract}({@link #union union(a,b)},{@link #intersection intersection(a,b)}) * or * {@link #union union}({@link #subtract subtract(a,b)},{@link #subtract subtract(b,a)}). * * @param a the first collection, must not be null * @param b the second collection, must not be null * @return the symmetric difference of the two collections15 */ public static Collection disjunction(final Collection a, final Collection b) { ArrayList list = new ArrayList(); Map mapa = getCardinalityMap(a); Map mapb = getCardinalityMap(b); Set elts = new HashSet(a); elts.addAll(b); Iterator it = elts.iterator(); while (it.hasNext()) { E obj = it.next(); for (int i = 0, m = ((Math.max(getFreq(obj, mapa), getFreq(obj, mapb))) - (Math.min(getFreq(obj, mapa), getFreq(obj, mapb)))); i < m; i++) { list.add(obj); } } return list; } /** * Returns a new {@link Collection} containing a - b. * The cardinality of each element e in the returned {@link Collection} * will be the cardinality of e in a minus the cardinality * of e in b, or zero, whichever is greater. * * @param a the collection to subtract from, must not be null * @param b the {@link Iterable} to subtract, must not be null * @return a new collection with the results * @see Collection#removeAll */ public static Collection subtract(final Collection a, final Iterable b) { ArrayList list = new ArrayList(a); for (E e : b) { list.remove(e); } return list; } /** * Returns true iff at least one element is in both collections15. *

      * In other words, this method returns true iff the * {@link #intersection} of coll1 and coll2 is not empty. * * @param coll1 the first collection, must not be null * @param coll2 the first collection, must not be null * @return true iff the intersection of the collections15 is non-empty * @see #intersection * @since 2.1 */ public static boolean containsAny(final Collection coll1, final Collection coll2) { if (coll1.size() < coll2.size()) { for (Iterator it = coll1.iterator(); it.hasNext();) { if (coll2.contains(it.next())) { return true; } } } else { for (Iterator it = coll2.iterator(); it.hasNext();) { if (coll1.contains(it.next())) { return true; } } } return false; } public static void main(String[] args) { List l1 = new ArrayList(); l1.add("Test"); List l2 = new ArrayList(); l2.add(1); containsAny(l1, l2); } /** * Returns a {@link Map} mapping each unique element in the given * {@link Iterable} to an {@link Integer} representing the number * of occurrences of that element in the {@link Iterable}. *

      * Only those elements present in the Iterable will appear as * keys in the map. * * @param iterable the collection to get the cardinality map for, must not be null * @return the populated cardinality map */ public static Map getCardinalityMap(final Iterable iterable) { Map count = new HashMap(); for (Iterator it = iterable.iterator(); it.hasNext();) { E obj = it.next(); Integer c = count.get(obj); if (c == null) { count.put(obj, INTEGER_ONE); } else { count.put(obj, new Integer(c.intValue() + 1)); } } return count; } /** * Returns true iff a is a sub-collection of b, * that is, iff the cardinality of e in a is less * than or equal to the cardinality of e in b, * for each element e in a. * * @param a the first (sub?) collection, must not be null * @param b the second (super?) collection, must not be null * @return true iff a is a sub-collection of b * @see #isProperSubCollection * @see Collection#containsAll */ public static boolean isSubCollection(final Iterable a, final Iterable b) { Map mapa = getCardinalityMap(a); Map mapb = getCardinalityMap(b); for (E obj : a) { if (getFreq(obj, mapa) > getFreq(obj, mapb)) { return false; } } return true; } /** * Returns true iff a is a proper sub-collection of b, * that is, iff the cardinality of e in a is less * than or equal to the cardinality of e in b, * for each element e in a, and there is at least one * element f such that the cardinality of f in b * is strictly greater than the cardinality of f in a. *

      * The implementation assumes *

        *
      • a.size() and b.size() represent the * total cardinality of a and b, resp.
      • *
      • a.size() < Integer.MAXVALUE
      • *
      * * @param a the first (sub?) collection, must not be null * @param b the second (super?) collection, must not be null * @return true iff a is a proper sub-collection of b * @see #isSubCollection * @see Collection#containsAll */ public static boolean isProperSubCollection(final Collection a, final Collection b) { return (a.size() < b.size()) && CollectionUtils.isSubCollection(a, b); } /** * Returns true iff the given {@link Collection}s contain * exactly the same elements with exactly the same cardinalities. *

      * That is, iff the cardinality of e in a is * equal to the cardinality of e in b, * for each element e in a or b. * * @param a the first collection, must not be null * @param b the second collection, must not be null * @return true iff the collections15 contain the same elements with the same cardinalities. */ public static boolean isEqualCollection(final Collection a, final Collection b) { if (a.size() != b.size()) { return false; } else { Map mapa = getCardinalityMap(a); Map mapb = getCardinalityMap(b); if (mapa.size() != mapb.size()) { return false; } else { Iterator it = mapa.keySet().iterator(); while (it.hasNext()) { Object obj = it.next(); if (getFreq(obj, mapa) != getFreq(obj, mapb)) { return false; } } return true; } } } /** * Returns the number of occurrences of obj in coll. * * @param obj the object to find the cardinality of * @param coll the collection to search * @return the the number of occurrences of obj in coll */ public static int cardinality(E obj, final Collection coll) { if (coll instanceof Set) { return (coll.contains(obj) ? 1 : 0); } if (coll instanceof Bag) { return ((Bag) coll).getCount(obj); } int count = 0; if (obj == null) { for (Iterator it = coll.iterator(); it.hasNext();) { if (it.next() == null) { count++; } } } else { for (Iterator it = coll.iterator(); it.hasNext();) { if (obj.equals(it.next())) { count++; } } } return count; } /** * Finds the first element in the given iterable which matches the given predicate. *

      * If the input iterable or predicate is null, or no element of the iterable * matches the predicate, null is returned. * * @param iterable the iterable to search, may be null * @param predicate the predicate to use, may be null * @return the first element of the iterable which matches the predicate or null if none could be found */ public static E find(Iterable iterable, Predicate predicate) { if (iterable != null && predicate != null) { for (Iterator iter = iterable.iterator(); iter.hasNext();) { E item = iter.next(); if (predicate.evaluate(item)) { return item; } } } return null; } /** * Executes the given closure on each element in the iterable. *

      * If the input iterable or closure is null, there is no change made. * * @param iterable the iterable to get the input from, may be null * @param closure the closure to perform, may be null */ public static void forAllDo(Iterable iterable, Closure closure) { if (iterable != null && closure != null) { for (Iterator it = iterable.iterator(); it.hasNext();) { closure.execute(it.next()); } } } /** * Filter the iterable by applying a Predicate to each element. If the * predicate returns false, remove the element. *

      * If the input iterable or predicate is null, there is no change made. * * @param iterable the iterable to get the input from, may be null * @param predicate the predicate to use as a filter, may be null */ public static void filter(Iterable iterable, Predicate predicate) { if (iterable != null && predicate != null) { for (Iterator it = iterable.iterator(); it.hasNext();) { if (predicate.evaluate(it.next()) == false) { it.remove(); } } } } /** * Transform the collection by applying a Transformer to each element. *

      * If the input collection or transformer is null, there is no change made. *

      * This routine is best for Lists, for which set() is used to do the * transformations "in place." For other Collections, clear() and addAll() * are used to replace elements. *

      * If the input collection controls its input, such as a Set, and the * Transformer creates duplicates (or are otherwise invalid), the * collection may reduce in size due to calling this method. * * @param collection the collection to get the input from, may be null * @param transformer the transformer to perform, may be null */ public static void transform(Collection collection, Transformer transformer) { if (collection != null && transformer != null) { if (collection instanceof List) { List list = (List) collection; for (ListIterator it = list.listIterator(); it.hasNext();) { it.set(transformer.transform(it.next())); } } else { Collection resultCollection = collect(collection, transformer); collection.clear(); collection.addAll(resultCollection); } } } /** * Counts the number of elements in the input collection that match the predicate. *

      * A null collection or predicate matches no elements. * * @param inputIterable the collection to get the input from, may be null * @param predicate the predicate to use, may be null * @return the number of matches for the predicate in the collection */ public static int countMatches(Iterable inputIterable, Predicate predicate) { int count = 0; if (inputIterable != null && predicate != null) { for (Iterator it = inputIterable.iterator(); it.hasNext();) { if (predicate.evaluate(it.next())) { count++; } } } return count; } /** * Answers true if a predicate is true for at least one element of a iterable. *

      * A null iterable or predicate returns false. * * @param iterable the iterable to get the input from, may be null * @param predicate the predicate to use, may be null * @return true if at least one element of the iterable matches the predicate */ public static boolean exists(Iterable iterable, Predicate predicate) { if (iterable != null && predicate != null) { for (Iterator it = iterable.iterator(); it.hasNext();) { if (predicate.evaluate(it.next())) { return true; } } } return false; } /** * Selects all elements from input collection which match the given predicate * into an output collection. *

      * A null predicate matches no elements. * * @param inputCollection the collection to get the input from, may not be null * @param predicate the predicate to use, may be null * @return the elements matching the predicate (new list) * @throws NullPointerException if the input collection is null */ public static Collection select(Collection inputCollection, Predicate predicate) { return select(inputCollection, predicate, new ArrayList(inputCollection.size())); } /** * Selects all elements from input collection which match the given predicate * and adds them to outputCollection. *

      * If the input collection or predicate is null, there is no change to the * output collection. * * @param inputCollection the collection to get the input from, may be null * @param predicate the predicate to use, may be null * @param outputCollection the collection to output into, may not be null */ public static > C select(Iterable inputCollection, Predicate predicate, C outputCollection) { if (inputCollection != null && predicate != null) { for (Iterator iter = inputCollection.iterator(); iter.hasNext();) { E item = iter.next(); if (predicate.evaluate(item)) { outputCollection.add(item); } } } return outputCollection; } /** * Selects all elements from inputCollection which don't match the given predicate * into an output collection. *

      * If the input predicate is null, the result is an empty list. * * @param inputCollection the collection to get the input from, may not be null * @param predicate the predicate to use, may be null * @return the elements not matching the predicate (new list) * @throws NullPointerException if the input collection is null */ public static Collection selectRejected(Collection inputCollection, Predicate predicate) { ArrayList answer = new ArrayList(inputCollection.size()); selectRejected(inputCollection, predicate, answer); return answer; } /** * Selects all elements from inputIterable which don't match the given predicate * and adds them to outputCollection. *

      * If the input predicate is null, no elements are added to outputCollection. * * @param inputIterable the collection to get the input from, may be null * @param predicate the predicate to use, may be null * @param outputCollection the collection to output into, may not be null */ public static void selectRejected(Iterable inputIterable, Predicate predicate, Collection outputCollection) { if (inputIterable != null && predicate != null) { for (Iterator iter = inputIterable.iterator(); iter.hasNext();) { E item = iter.next(); if (predicate.evaluate(item) == false) { outputCollection.add(item); } } } } /** * Returns a new Collection consisting of the elements of inputCollection transformed * by the given transformer. *

      * If the input transformer is null, the result is an empty list. * * @param inputCollection the collection to get the input from, may not be null * @param transformer the transformer to use, may be null * @return the transformed result (new list) * @throws NullPointerException if the input collection is null */ public static Collection collect(Collection inputCollection, Transformer transformer) { ArrayList answer = new ArrayList(inputCollection.size()); collect(inputCollection, transformer, answer); return answer; } /** * Transforms all elements from the inputIterator with the given transformer * and adds them to the outputCollection. *

      * If the input iterator or transformer is null, the result is an empty list. * * @param inputIterator the iterator to get the input from, may be null * @param transformer the transformer to use, may be null * @return the transformed result (new list) */ public static Collection collect(Iterator inputIterator, Transformer transformer) { ArrayList answer = new ArrayList(); collect(inputIterator, transformer, answer); return answer; } /** * Transforms all elements from inputCollection with the given transformer * and adds them to the outputCollection. *

      * If the input collection or transformer is null, there is no change to the * output collection. * * @param inputCollection the collection to get the input from, may be null * @param transformer the transformer to use, may not be null * @param outputCollection the collection to output into, may not be null * @return the outputCollection with the transformed input added * @throws NullPointerException if the output collection is null */ public static > C collect(Iterable inputCollection, final Transformer transformer, final C outputCollection) { if (inputCollection != null) { return collect(inputCollection.iterator(), transformer, outputCollection); } return outputCollection; } /** * Transforms all elements from the inputIterator with the given transformer * and adds them to the outputCollection. *

      * If the input iterator or transformer is null, there is no change to the * output collection. * * @param inputIterator the iterator to get the input from, may be null * @param transformer the transformer to use, may not be null * @param outputCollection the collection to output into, may not be null * @return the outputCollection with the transformed input added * @throws NullPointerException if the output collection is null */ public static > C collect(Iterator inputIterator, final Transformer transformer, final C outputCollection) { if (inputIterator != null && transformer != null) { while (inputIterator.hasNext()) { I item = inputIterator.next(); O value = transformer.transform(item); outputCollection.add(value); } } return outputCollection; } /** * Adds all elements in the iteration to the given collection. * @deprecated Replaced by {@link Collection#addAll(java.util.Collection)} * * @param collection the collection to add to * @param iterator the iterator of elements to add, may not be null * @throws NullPointerException if the collection or iterator is null */ public static void addAll(Collection collection, Iterator iterator) { while (iterator.hasNext()) { collection.add(iterator.next()); } } /** * Adds all elements in the enumeration to the given collection. * @deprecated Replaced by {@link Collection#addAll(java.util.Collection)} * * @param collection the collection to add to * @param enumeration the enumeration of elements to add, may not be null * @throws NullPointerException if the collection or enumeration is null */ public static void addAll(Collection collection, Enumeration enumeration) { while (enumeration.hasMoreElements()) { collection.add(enumeration.nextElement()); } } /** * Adds all elements in the array to the given collection. * * @param collection the collection to add to, may not be null * @param elements the array of elements to add, may not be null * @throws NullPointerException if the collection or array is null */ public static void addAll(Collection collection, T... elements) { for (int i = 0, size = elements.length; i < size; i++) { collection.add(elements[i]); } } /** * Given an Object, and an index, returns the nth value in the * object. *

        *
      • If obj is a Map, returns the nth value from the keySet iterator, unless * the Map contains an Integer key with integer value = idx, in which case the * corresponding map entry value is returned. If idx exceeds the number of entries in * the map, an empty Iterator is returned. *
      • If obj is a List or an array, returns the nth value, throwing IndexOutOfBoundsException, * ArrayIndexOutOfBoundsException, resp. if the nth value does not exist. *
      • If obj is an iterator, enumeration or Collection, returns the nth value from the iterator, * returning an empty Iterator (resp. Enumeration) if the nth value does not exist. *
      • Returns the original obj if it is null or not a Collection or Iterator. *
      * * @param obj the object to get an index of, may be null * @param idx the index to get * @throws IndexOutOfBoundsException * @throws ArrayIndexOutOfBoundsException * @deprecated use {@link #get(Object, int)} instead. Will be removed in v4.0 */ public static Object index(Object obj, int idx) { return index(obj, new Integer(idx)); } /** * Given an Object, and a key (index), returns the value associated with * that key in the Object. The following checks are made: *
        *
      • If obj is a Map, use the index as a key to get a value. If no match continue. *
      • Check key is an Integer. If not, return the object passed in. *
      • If obj is a Map, get the nth value from the keySet iterator. * If the Map has fewer than n entries, return an empty Iterator. *
      • If obj is a List or an array, get the nth value, throwing IndexOutOfBoundsException, * ArrayIndexOutOfBoundsException, resp. if the nth value does not exist. *
      • If obj is an iterator, enumeration or Collection, get the nth value from the iterator, * returning an empty Iterator (resp. Enumeration) if the nth value does not exist. *
      • Return the original obj. *
      * * @param obj the object to get an index of * @param index the index to get * @return the object at the specified index * @throws IndexOutOfBoundsException * @throws ArrayIndexOutOfBoundsException * @deprecated use {@link #get(Object, int)} instead. Will be removed in v4.0 */ public static Object index(Object obj, Object index) { if (obj instanceof Map) { Map map = (Map) obj; if (map.containsKey(index)) { return map.get(index); } } int idx = -1; if (index instanceof Integer) { idx = ((Integer) index).intValue(); } if (idx < 0) { return obj; } else if (obj instanceof Map) { Map map = (Map) obj; Iterator iterator = map.keySet().iterator(); return index(iterator, idx); } else if (obj instanceof List) { return ((List) obj).get(idx); } else if (obj instanceof Object[]) { return ((Object[]) obj)[idx]; } else if (obj instanceof Enumeration) { Enumeration it = (Enumeration) obj; while (it.hasMoreElements()) { idx--; if (idx == -1) { return it.nextElement(); } else { it.nextElement(); } } } else if (obj instanceof Iterator) { return index((Iterator) obj, idx); } else if (obj instanceof Collection) { Iterator iterator = ((Collection) obj).iterator(); return index(iterator, idx); } return obj; } private static Object index(Iterator iterator, int idx) { while (iterator.hasNext()) { idx--; if (idx == -1) { return iterator.next(); } else { iterator.next(); } } return iterator; } /** * Returns the index-th value in object, throwing * IndexOutOfBoundsException if there is no such element or * IllegalArgumentException if object is not an * instance of one of the supported types. *

      * The supported types, and associated semantics are: *

        *
      • Map -- the value returned is the Map.Entry in position * index in the map's entrySet iterator, * if there is such an entry.
      • *
      • List -- this method is equivalent to the list's get method.
      • *
      • Array -- the index-th array entry is returned, * if there is such an entry; otherwise an IndexOutOfBoundsException * is thrown.
      • *
      • Collection -- the value returned is the index-th object * returned by the collection's default iterator, if there is such an element.
      • *
      • Iterator or Enumeration -- the value returned is the * index-th object in the Iterator/Enumeration, if there * is such an element. The Iterator/Enumeration is advanced to * index (or to the end, if index exceeds the * number of entries) as a side effect of this method.
      • *
      * * @param object the object to get a value from * @param index the index to get * @return the object at the specified index * @throws IndexOutOfBoundsException if the index is invalid * @throws IllegalArgumentException if the object type is invalid */ public static Object get(Object object, int index) { if (index < 0) { throw new IndexOutOfBoundsException("Index cannot be negative: " + index); } if (object instanceof Map) { Map map = (Map) object; Iterator iterator = map.entrySet().iterator(); return get(iterator, index); } else if (object instanceof List) { return ((List) object).get(index); } else if (object instanceof Object[]) { return ((Object[]) object)[index]; } else if (object instanceof Iterator) { Iterator it = (Iterator) object; while (it.hasNext()) { index--; if (index == -1) { return it.next(); } else { it.next(); } } throw new IndexOutOfBoundsException("Entry does not exist: " + index); } else if (object instanceof Collection) { Iterator iterator = ((Collection) object).iterator(); return get(iterator, index); } else if (object instanceof Enumeration) { Enumeration it = (Enumeration) object; while (it.hasMoreElements()) { index--; if (index == -1) { return it.nextElement(); } else { it.nextElement(); } } throw new IndexOutOfBoundsException("Entry does not exist: " + index); } else if (object == null) { throw new IllegalArgumentException("Unsupported object type: null"); } else { try { return Array.get(object, index); } catch (IllegalArgumentException ex) { throw new IllegalArgumentException("Unsupported object type: " + object.getClass().getName()); } } } /** * Gets the size of the collection/iterator specified. *

      * This method can handles objects as follows *

        *
      • Collection - the collection size *
      • Map - the map size *
      • Array - the array size *
      • Iterator - the number of elements remaining in the iterator *
      • Enumeration - the number of elements remaining in the enumeration *
      * * @param object the object to get the size of * @return the size of the specified collection * @throws IllegalArgumentException thrown if object is not recognised or null * @since Commons Collections 3.1 */ public static int size(Object object) { int total = 0; if (object instanceof Map) { total = ((Map) object).size(); } else if (object instanceof Collection) { total = ((Collection) object).size(); } else if (object instanceof Object[]) { total = ((Object[]) object).length; } else if (object instanceof Iterator) { Iterator it = (Iterator) object; while (it.hasNext()) { total++; it.next(); } } else if (object instanceof Enumeration) { Enumeration it = (Enumeration) object; while (it.hasMoreElements()) { total++; it.nextElement(); } } else if (object == null) { throw new IllegalArgumentException("Unsupported object type: null"); } else { try { total = Array.getLength(object); } catch (IllegalArgumentException ex) { throw new IllegalArgumentException("Unsupported object type: " + object.getClass().getName()); } } return total; } /** * Reverses the order of the given array. * * @param array the array to reverse */ public static void reverseArray(Object[] array) { int i = 0; int j = array.length - 1; Object tmp; while (j > i) { tmp = array[j]; array[j] = array[i]; array[i] = tmp; j--; i++; } } private static final int getFreq(final Object obj, final Map freqMap) { Integer count = (Integer) freqMap.get(obj); if (count != null) { return count.intValue(); } return 0; } /** * Returns true if no more elements can be added to the Collection. *

      * This method uses the {@link BoundedCollection} interface to determine the * full status. If the collection does not implement this interface then * false is returned. *

      * The collection does not have to implement this interface directly. * If the collection has been decorated using the decorators subpackage * then these will be removed to access the BoundedCollection. * * @param coll the collection to check * @return true if the BoundedCollection is full * @throws NullPointerException if the collection is null */ public static boolean isFull(Collection coll) { if (coll == null) { throw new NullPointerException("The collection must not be null"); } if (coll instanceof BoundedCollection) { return ((BoundedCollection) coll).isFull(); } try { BoundedCollection bcoll = UnmodifiableBoundedCollection.decorateUsing(coll); return bcoll.isFull(); } catch (IllegalArgumentException ex) { return false; } } /** * Get the maximum number of elements that the Collection can contain. *

      * This method uses the {@link BoundedCollection} interface to determine the * maximum size. If the collection does not implement this interface then * -1 is returned. *

      * The collection does not have to implement this interface directly. * If the collection has been decorated using the decorators subpackage * then these will be removed to access the BoundedCollection. * * @param coll the collection to check * @return the maximum size of the BoundedCollection, -1 if no maximum size * @throws NullPointerException if the collection is null */ public static int maxSize(Collection coll) { if (coll == null) { throw new NullPointerException("The collection must not be null"); } if (coll instanceof BoundedCollection) { return ((BoundedCollection) coll).maxSize(); } try { BoundedCollection bcoll = UnmodifiableBoundedCollection.decorateUsing(coll); return bcoll.maxSize(); } catch (IllegalArgumentException ex) { return -1; } } //----------------------------------------------------------------------- /** * Returns a synchronized collection backed by the given collection. *

      * You must manually synchronize on the returned buffer's iterator to * avoid non-deterministic behavior: *

      *

           * Collection c = CollectionUtils.synchronizedCollection(myCollection);
           * synchronized (c) {
           *     Iterator i = c.iterator();
           *     while (i.hasNext()) {
           *         process (i.next());
           *     }
           * }
           * 
      *

      * This method uses the implementation in the decorators subpackage. * * @param collection the collection to synchronize, must not be null * @return a synchronized collection backed by the given collection * @throws IllegalArgumentException if the collection is null */ public static Collection synchronizedCollection(Collection collection) { return SynchronizedCollection.decorate(collection); } /** * Returns an unmodifiable collection backed by the given collection. *

      * This method uses the implementation in the decorators subpackage. * * @param collection the collection to make unmodifiable, must not be null * @return an unmodifiable collection backed by the given collection * @throws IllegalArgumentException if the collection is null */ public static Collection unmodifiableCollection(Collection collection) { return UnmodifiableCollection.decorate(collection); } /** * Returns a predicated (validating) collection backed by the given collection. *

      * Only objects that pass the test in the given predicate can be added to the collection. * Trying to add an invalid object results in an IllegalArgumentException. * It is important not to use the original collection after invoking this method, * as it is a backdoor for adding invalid objects. * * @param collection the collection to predicate, must not be null * @param predicate the predicate for the collection, must not be null * @return a predicated collection backed by the given collection * @throws IllegalArgumentException if the Collection is null */ public static Collection predicatedCollection(Collection collection, Predicate predicate) { return PredicatedCollection.decorate(collection, predicate); } /** * Returns a typed collection backed by the given collection. *

      * Only objects of the specified type can be added to the collection. * * @param collection the collection to limit to a specific type, must not be null * @param type the type of objects which may be added to the collection * @return a typed collection backed by the specified collection * @deprecated Obsoleted by Java 1.5 Generics. */ public static Collection typedCollection(Collection collection, Class type) { return TypedCollection.decorate(collection, type); } /** * Returns a transformed bag backed by the given collection. *

      * Each object is passed through the transformer as it is added to the * Collection. It is important not to use the original collection after invoking this * method, as it is a backdoor for adding untransformed objects. * * @param collection the collection to predicate, must not be null * @param transformer the transformer for the collection, must not be null * @return a transformed collection backed by the given collection * @throws IllegalArgumentException if the Collection or Transformer is null */ public static Collection transformedCollection(Collection collection, Transformer transformer) { return TransformedCollection.decorate(collection, transformer); } } collections-generic-4.01/src/java/org/apache/commons/collections15/IteratorUtils.java0000644000175000017500000010404410464140763031140 0ustar giovannigiovanni// GenericsNote: Converted, although getIterator(Object) is unsatisfying. /* * Copyright 2002-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15; import org.apache.commons.collections15.iterators.*; import java.lang.reflect.Array; import java.lang.reflect.Method; import java.util.*; /** * Provides static utility methods and decorators for {@link Iterator} * instances. The implementations are provided in the iterators subpackage. *

      * WARNING: Due to human error certain binary incompatabilities were introduced * between Commons Collections 2.1 and 3.0. The class remained source and test * compatible, so if you can recompile all your classes and dependencies * everything is OK. Those methods which are binary incompatible are marked as * such, together with alternate solutions that are binary compatible * against versions 2.1.1 and 3.1. * * @author Stephen Colebourne * @author Matt Hall, John Watkinson, Phil Steitz * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:19 $ * @since Commons Collections 2.1 */ public class IteratorUtils { // validation is done in this class in certain cases because the // public classes allow invalid states /** * An iterator over no elements. *

      * WARNING: This constant is binary incompatible with Commons Collections 2.1 and 2.1.1. * Use EmptyIterator.INSTANCE for compatability with Commons Collections 2.1.1. */ public static final ResettableIterator EMPTY_ITERATOR = EmptyIterator.RESETTABLE_INSTANCE; /** * A list iterator over no elements. *

      * WARNING: This constant is binary incompatible with Commons Collections 2.1 and 2.1.1. * Use EmptyListIterator.INSTANCE for compatability with Commons Collections 2.1.1. */ public static final ResettableListIterator EMPTY_LIST_ITERATOR = EmptyListIterator.RESETTABLE_INSTANCE; /** * An ordered iterator over no elements. */ public static final OrderedIterator EMPTY_ORDERED_ITERATOR = EmptyOrderedIterator.INSTANCE; /** * A map iterator over no elements. */ public static final MapIterator EMPTY_MAP_ITERATOR = EmptyMapIterator.INSTANCE; /** * An ordered map iterator over no elements. */ public static final OrderedMapIterator EMPTY_ORDERED_MAP_ITERATOR = EmptyOrderedMapIterator.INSTANCE; /** * IteratorUtils is not normally instantiated. */ public IteratorUtils() { } // Empty //----------------------------------------------------------------------- /** * Gets an empty iterator. *

      * This iterator is a valid iterator object that will iterate over * nothing. *

      * WARNING: This method is binary incompatible with Commons Collections 2.1 and 2.1.1. * Use EmptyIterator.INSTANCE for compatability with Commons Collections 2.1.1. * * @return an iterator over nothing */ public static ResettableIterator emptyIterator() { return EMPTY_ITERATOR; } /** * Gets an empty list iterator. *

      * This iterator is a valid list iterator object that will iterate * over nothing. *

      * WARNING: This method is binary incompatible with Commons Collections 2.1 and 2.1.1. * Use EmptyListIterator.INSTANCE for compatability with Commons Collections 2.1.1. * * @return a list iterator over nothing */ public static ResettableListIterator emptyListIterator() { return EMPTY_LIST_ITERATOR; } /** * Gets an empty ordered iterator. *

      * This iterator is a valid iterator object that will iterate * over nothing. * * @return an ordered iterator over nothing */ public static OrderedIterator emptyOrderedIterator() { return EMPTY_ORDERED_ITERATOR; } /** * Gets an empty map iterator. *

      * This iterator is a valid map iterator object that will iterate * over nothing. * * @return a map iterator over nothing */ public static MapIterator emptyMapIterator() { return EMPTY_MAP_ITERATOR; } /** * Gets an empty ordered map iterator. *

      * This iterator is a valid map iterator object that will iterate * over nothing. * * @return a map iterator over nothing */ public static OrderedMapIterator emptyOrderedMapIterator() { return EMPTY_ORDERED_MAP_ITERATOR; } // Singleton //----------------------------------------------------------------------- /** * Gets a singleton iterator. *

      * This iterator is a valid iterator object that will iterate over * the specified object. *

      * WARNING: This method is binary incompatible with Commons Collections 2.1 and 2.1.1. * Use new SingletonIterator(object) for compatability. * * @param object the single object over which to iterate * @return a singleton iterator over the object */ public static ResettableIterator singletonIterator(E object) { return new SingletonIterator(object); } /** * Gets a singleton list iterator. *

      * This iterator is a valid list iterator object that will iterate over * the specified object. * * @param object the single object over which to iterate * @return a singleton list iterator over the object */ public static ListIterator singletonListIterator(E object) { return new SingletonListIterator(object); } // Arrays //----------------------------------------------------------------------- /** * Gets an iterator over an object array. *

      * WARNING: This method is binary incompatible with Commons Collections 2.1 and 2.1.1. * Use new ArrayIterator(array) for compatability. * * @param array the array over which to iterate * @return an iterator over the array * @throws NullPointerException if array is null */ public static ResettableIterator arrayIterator(E[] array) { return new ObjectArrayIterator(array); } /** * Gets an iterator over an object or primitive array. *

      * This method will handle primitive arrays as well as object arrays. * The primitives will be wrapped in the appropriate wrapper class. * * @param array the array over which to iterate * @return an iterator over the array * @throws IllegalArgumentException if the array is not an array * @throws NullPointerException if array is null */ public static ResettableIterator arrayIterator(Object array) { return new ArrayIterator(array); } /** * Gets an iterator over the end part of an object array. *

      * WARNING: This method is binary incompatible with Commons Collections 2.1 and 2.1.1. * Use new ArrayIterator(array,start) for compatability. * * @param array the array over which to iterate * @param start the index to start iterating at * @return an iterator over part of the array * @throws IndexOutOfBoundsException if start is less than zero or greater * than the length of the array * @throws NullPointerException if array is null */ public static ResettableIterator arrayIterator(E[] array, int start) { return new ObjectArrayIterator(array, start); } /** * Gets an iterator over the end part of an object or primitive array. *

      * This method will handle primitive arrays as well as object arrays. * The primitives will be wrapped in the appropriate wrapper class. * * @param array the array over which to iterate * @param start the index to start iterating at * @return an iterator over part of the array * @throws IllegalArgumentException if the array is not an array * @throws IndexOutOfBoundsException if start is less than zero or greater * than the length of the array * @throws NullPointerException if array is null */ public static ResettableIterator arrayIterator(Object array, int start) { return new ArrayIterator(array, start); } /** * Gets an iterator over part of an object array. *

      * WARNING: This method is binary incompatible with Commons Collections 2.1 and 2.1.1. * Use new ArrayIterator(array,start,end) for compatability. * * @param array the array over which to iterate * @param start the index to start iterating at * @param end the index to finish iterating at * @return an iterator over part of the array * @throws IndexOutOfBoundsException if array bounds are invalid * @throws IllegalArgumentException if end is before start * @throws NullPointerException if array is null */ public static ResettableIterator arrayIterator(E[] array, int start, int end) { return new ObjectArrayIterator(array, start, end); } /** * Gets an iterator over part of an object or primitive array. *

      * This method will handle primitive arrays as well as object arrays. * The primitives will be wrapped in the appropriate wrapper class. * * @param array the array over which to iterate * @param start the index to start iterating at * @param end the index to finish iterating at * @return an iterator over part of the array * @throws IllegalArgumentException if the array is not an array * @throws IndexOutOfBoundsException if array bounds are invalid * @throws IllegalArgumentException if end is before start * @throws NullPointerException if array is null */ public static ResettableIterator arrayIterator(Object array, int start, int end) { return new ArrayIterator(array, start, end); } //----------------------------------------------------------------------- /** * Gets a list iterator over an object array. * * @param array the array over which to iterate * @return a list iterator over the array * @throws NullPointerException if array is null */ public static ResettableListIterator arrayListIterator(E[] array) { return new ObjectArrayListIterator(array); } /** * Gets a list iterator over an object or primitive array. *

      * This method will handle primitive arrays as well as object arrays. * The primitives will be wrapped in the appropriate wrapper class. * * @param array the array over which to iterate * @return a list iterator over the array * @throws IllegalArgumentException if the array is not an array * @throws NullPointerException if array is null */ public static ResettableListIterator arrayListIterator(Object array) { return new ArrayListIterator(array); } /** * Gets a list iterator over the end part of an object array. * * @param array the array over which to iterate * @param start the index to start iterating at * @return a list iterator over part of the array * @throws IndexOutOfBoundsException if start is less than zero * @throws NullPointerException if array is null */ public static ResettableListIterator arrayListIterator(E[] array, int start) { return new ObjectArrayListIterator(array, start); } /** * Gets a list iterator over the end part of an object or primitive array. *

      * This method will handle primitive arrays as well as object arrays. * The primitives will be wrapped in the appropriate wrapper class. * * @param array the array over which to iterate * @param start the index to start iterating at * @return a list iterator over part of the array * @throws IllegalArgumentException if the array is not an array * @throws IndexOutOfBoundsException if start is less than zero * @throws NullPointerException if array is null */ public static ResettableListIterator arrayListIterator(Object array, int start) { return new ArrayListIterator(array, start); } /** * Gets a list iterator over part of an object array. * * @param array the array over which to iterate * @param start the index to start iterating at * @param end the index to finish iterating at * @return a list iterator over part of the array * @throws IndexOutOfBoundsException if array bounds are invalid * @throws IllegalArgumentException if end is before start * @throws NullPointerException if array is null */ public static ResettableListIterator arrayListIterator(E[] array, int start, int end) { return new ObjectArrayListIterator(array, start, end); } /** * Gets a list iterator over part of an object or primitive array. *

      * This method will handle primitive arrays as well as object arrays. * The primitives will be wrapped in the appropriate wrapper class. * * @param array the array over which to iterate * @param start the index to start iterating at * @param end the index to finish iterating at * @return a list iterator over part of the array * @throws IllegalArgumentException if the array is not an array * @throws IndexOutOfBoundsException if array bounds are invalid * @throws IllegalArgumentException if end is before start * @throws NullPointerException if array is null */ public static ResettableListIterator arrayListIterator(Object array, int start, int end) { return new ArrayListIterator(array, start, end); } // Unmodifiable //----------------------------------------------------------------------- /** * Gets an immutable version of an {@link Iterator}. The returned object * will always throw an {@link UnsupportedOperationException} for * the {@link Iterator#remove} method. * * @param iterator the iterator to make immutable * @return an immutable version of the iterator */ public static Iterator unmodifiableIterator(Iterator iterator) { return UnmodifiableIterator.decorate(iterator); } /** * Gets an immutable version of a {@link ListIterator}. The returned object * will always throw an {@link UnsupportedOperationException} for * the {@link Iterator#remove}, {@link ListIterator#add} and * {@link ListIterator#set} methods. * * @param listIterator the iterator to make immutable * @return an immutable version of the iterator */ public static ListIterator unmodifiableListIterator(ListIterator listIterator) { return UnmodifiableListIterator.decorate(listIterator); } /** * Gets an immutable version of a {@link MapIterator}. The returned object * will always throw an {@link UnsupportedOperationException} for * the {@link Iterator#remove}, {@link MapIterator#setValue(Object)} methods. * * @param mapIterator the iterator to make immutable * @return an immutable version of the iterator */ public static MapIterator unmodifiableMapIterator(MapIterator mapIterator) { return UnmodifiableMapIterator.decorate(mapIterator); } // Chained //----------------------------------------------------------------------- /** * Gets an iterator that iterates through two {@link Iterator}s * one after another. * * @param iterator1 the first iterators to use, not null * @param iterator2 the first iterators to use, not null * @return a combination iterator over the iterators * @throws NullPointerException if either iterator is null */ public static Iterator chainedIterator(Iterator iterator1, Iterator iterator2) { return new IteratorChain(iterator1, iterator2); } /** * Gets an iterator that iterates through an array of {@link Iterator}s * one after another. * * @param iterators the iterators to use, not null or empty or contain nulls * @return a combination iterator over the iterators * @throws NullPointerException if iterators array is null or contains a null */ public static Iterator chainedIterator(Iterator[] iterators) { return new IteratorChain(iterators); } /** * Gets an iterator that iterates through a collections15 of {@link Iterator}s * one after another. * * @param iterators the iterators to use, not null or empty or contain nulls * @return a combination iterator over the iterators * @throws NullPointerException if iterators collection is null or contains a null * @throws ClassCastException if the iterators collection contains the wrong object type */ public static Iterator chainedIterator(Collection> iterators) { return new IteratorChain(iterators); } // Collated //----------------------------------------------------------------------- /** * Gets an iterator that provides an ordered iteration over the elements * contained in a collection of ordered {@link Iterator}s. *

      * Given two ordered {@link Iterator}s A and B, * the {@link Iterator#next()} method will return the lesser of * A.next() and B.next(). *

      * The comparator is optional. If null is specified then natural order is used. * * @param comparator the comparator to use, may be null for natural order * @param iterator1 the first iterators to use, not null * @param iterator2 the first iterators to use, not null * @return a combination iterator over the iterators * @throws NullPointerException if either iterator is null */ public static Iterator collatedIterator(Comparator comparator, Iterator iterator1, Iterator iterator2) { return new CollatingIterator(comparator, iterator1, iterator2); } /** * Gets an iterator that provides an ordered iteration over the elements * contained in an array of {@link Iterator}s. *

      * Given two ordered {@link Iterator}s A and B, * the {@link Iterator#next()} method will return the lesser of * A.next() and B.next() and so on. *

      * The comparator is optional. If null is specified then natural order is used. * * @param comparator the comparator to use, may be null for natural order * @param iterators the iterators to use, not null or empty or contain nulls * @return a combination iterator over the iterators * @throws NullPointerException if iterators array is null or contains a null */ public static Iterator collatedIterator(Comparator comparator, Iterator[] iterators) { return new CollatingIterator(comparator, iterators); } /** * Gets an iterator that provides an ordered iteration over the elements * contained in a collection of {@link Iterator}s. *

      * Given two ordered {@link Iterator}s A and B, * the {@link Iterator#next()} method will return the lesser of * A.next() and B.next() and so on. *

      * The comparator is optional. If null is specified then natural order is used. * * @param comparator the comparator to use, may be null for natural order * @param iterators the iterators to use, not null or empty or contain nulls * @return a combination iterator over the iterators * @throws NullPointerException if iterators collection is null or contains a null * @throws ClassCastException if the iterators collection contains the wrong object type */ public static Iterator collatedIterator(Comparator comparator, Collection> iterators) { return new CollatingIterator(comparator, iterators); } // Object Graph //----------------------------------------------------------------------- /** * Gets an iterator that operates over an object graph. *

      * This iterator can extract multiple objects from a complex tree-like object graph. * The iteration starts from a single root object. * It uses a Transformer to extract the iterators and elements. * Its main benefit is that no intermediate List is created. *

      * For example, consider an object graph: *

           *                 |- Branch -- Leaf
           *                 |         \- Leaf
           *         |- Tree |         /- Leaf
           *         |       |- Branch -- Leaf
           *  Forest |                 \- Leaf
           *         |       |- Branch -- Leaf
           *         |       |         \- Leaf
           *         |- Tree |         /- Leaf
           *                 |- Branch -- Leaf
           *                 |- Branch -- Leaf
      * The following Transformer, used in this class, will extract all * the Leaf objects without creating a combined intermediate list: *
           * public Object transform(Object input) {
           *   if (input instanceof Forest) {
           *     return ((Forest) input).treeIterator();
           *   }
           *   if (input instanceof Tree) {
           *     return ((Tree) input).branchIterator();
           *   }
           *   if (input instanceof Branch) {
           *     return ((Branch) input).leafIterator();
           *   }
           *   if (input instanceof Leaf) {
           *     return input;
           *   }
           *   throw new ClassCastException();
           * }
      *

      * Internally, iteration starts from the root object. When next is called, * the transformer is called to examine the object. The transformer will return * either an iterator or an object. If the object is an Iterator, the next element * from that iterator is obtained and the process repeats. If the element is an object * it is returned. *

      * Under many circumstances, linking Iterators together in this manner is * more efficient (and convenient) than using nested for loops to extract a list. * * @param root the root object to start iterating from, null results in an empty iterator * @param transformer the transformer to use, see above, null uses no effect transformer * @return a new object graph iterator * @since Commons Collections 3.1 */ public static Iterator objectGraphIterator(Object root, Transformer transformer) { return new ObjectGraphIterator(root, transformer); } // Transformed //----------------------------------------------------------------------- /** * Gets an iterator that transforms the elements of another iterator. *

      * The transformation occurs during the next() method and the underlying * iterator is unaffected by the transformation. * * @param iterator the iterator to use, not null * @param transform the transform to use, not null * @return a new transforming iterator * @throws NullPointerException if either parameter is null */ public static Iterator transformedIterator(Iterator iterator, Transformer transform) { if (iterator == null) { throw new NullPointerException("Iterator must not be null"); } if (transform == null) { throw new NullPointerException("Transformer must not be null"); } return new TransformIterator(iterator, transform); } // Filtered //----------------------------------------------------------------------- /** * Gets an iterator that filters another iterator. *

      * The returned iterator will only return objects that match the specified * filtering predicate. * * @param iterator the iterator to use, not null * @param predicate the predicate to use as a filter, not null * @return a new filtered iterator * @throws NullPointerException if either parameter is null */ public static Iterator filteredIterator(Iterator iterator, Predicate predicate) { if (iterator == null) { throw new NullPointerException("Iterator must not be null"); } if (predicate == null) { throw new NullPointerException("Predicate must not be null"); } return new FilterIterator(iterator, predicate); } /** * Gets a list iterator that filters another list iterator. *

      * The returned iterator will only return objects that match the specified * filtering predicate. * * @param listIterator the list iterator to use, not null * @param predicate the predicate to use as a filter, not null * @return a new filtered iterator * @throws NullPointerException if either parameter is null */ public static ListIterator filteredListIterator(ListIterator listIterator, Predicate predicate) { if (listIterator == null) { throw new NullPointerException("ListIterator must not be null"); } if (predicate == null) { throw new NullPointerException("Predicate must not be null"); } return new FilterListIterator(listIterator, predicate); } // Looping //----------------------------------------------------------------------- /** * Gets an iterator that loops continuously over the supplied collection. *

      * The iterator will only stop looping if the remove method is called * enough times to empty the collection, or if the collection is empty * to start with. * * @param coll the collection to iterate over, not null * @return a new looping iterator * @throws NullPointerException if the collection is null */ public static ResettableIterator loopingIterator(Collection coll) { if (coll == null) { throw new NullPointerException("Collection must not be null"); } return new LoopingIterator(coll); } // Views //----------------------------------------------------------------------- /** * Gets an iterator that provides an iterator view of the given enumeration. * * @param enumeration the enumeration to use * @return a new iterator */ public static Iterator asIterator(Enumeration enumeration) { if (enumeration == null) { throw new NullPointerException("Enumeration must not be null"); } return new EnumerationIterator(enumeration); } /** * Gets an iterator that provides an iterator view of the given enumeration * that will remove elements from the specified collection. * * @param enumeration the enumeration to use * @param removeCollection the collection to remove elements from * @return a new iterator */ public static Iterator asIterator(Enumeration enumeration, Collection removeCollection) { if (enumeration == null) { throw new NullPointerException("Enumeration must not be null"); } if (removeCollection == null) { throw new NullPointerException("Collection must not be null"); } return new EnumerationIterator(enumeration, removeCollection); } /** * Gets an enumeration that wraps an iterator. * * @param iterator the iterator to use, not null * @return a new enumeration * @throws NullPointerException if iterator is null */ public static Enumeration asEnumeration(Iterator iterator) { if (iterator == null) { throw new NullPointerException("Iterator must not be null"); } return new IteratorEnumeration(iterator); } /** * Gets a list iterator based on a simple iterator. *

      * As the wrapped Iterator is traversed, a LinkedList of its values is * cached, permitting all required operations of ListIterator. * * @param iterator the iterator to use, not null * @return a new iterator * @throws NullPointerException if iterator parameter is null */ public static ListIterator toListIterator(Iterator iterator) { if (iterator == null) { throw new NullPointerException("Iterator must not be null"); } return new ListIteratorWrapper(iterator); } /** * Gets an array based on an iterator. *

      * As the wrapped Iterator is traversed, an ArrayList of its values is * created. At the end, this is converted to an array. * * @param iterator the iterator to use, not null * @return an array of the iterator contents * @throws NullPointerException if iterator parameter is null */ public static E[] toArray(Iterator iterator) { if (iterator == null) { throw new NullPointerException("Iterator must not be null"); } List list = toList(iterator, 100); return (E[]) list.toArray(); } /** * Gets an array based on an iterator. *

      * As the wrapped Iterator is traversed, an ArrayList of its values is * created. At the end, this is converted to an array. * * @param iterator the iterator to use, not null * @param arrayClass the class of array to create * @return an array of the iterator contents * @throws NullPointerException if iterator parameter is null * @throws NullPointerException if arrayClass is null * @throws ClassCastException if the arrayClass is invalid */ public static E[] toArray(Iterator iterator, Class arrayClass) { if (iterator == null) { throw new NullPointerException("Iterator must not be null"); } if (arrayClass == null) { throw new NullPointerException("Array class must not be null"); } List list = toList(iterator, 100); return list.toArray((E[]) Array.newInstance(arrayClass, list.size())); } /** * Gets a list based on an iterator. *

      * As the wrapped Iterator is traversed, an ArrayList of its values is * created. At the end, the list is returned. * * @param iterator the iterator to use, not null * @return a list of the iterator contents * @throws NullPointerException if iterator parameter is null */ public static List toList(Iterator iterator) { return toList(iterator, 10); } /** * Gets a list based on an iterator. *

      * As the wrapped Iterator is traversed, an ArrayList of its values is * created. At the end, the list is returned. * * @param iterator the iterator to use, not null * @param estimatedSize the initial size of the ArrayList * @return a list of the iterator contents * @throws NullPointerException if iterator parameter is null * @throws IllegalArgumentException if the size is less than 1 */ public static List toList(Iterator iterator, int estimatedSize) { if (iterator == null) { throw new NullPointerException("Iterator must not be null"); } if (estimatedSize < 1) { throw new IllegalArgumentException("Estimated size must be greater than 0"); } List list = new ArrayList(estimatedSize); while (iterator.hasNext()) { list.add(iterator.next()); } return list; } /** * Gets a suitable Iterator for the given object. *

      * This method can handles objects as follows *

        *
      • null - empty iterator *
      • Iterator - returned directly *
      • Enumeration - wrapped *
      • Collection - iterator from collection returned *
      • Map - values iterator returned *
      • Dictionary - values (elements) enumeration returned as iterator *
      • array - iterator over array returned *
      • object with iterator() public method accessed by reflection *
      • object - singleton iterator *
      * * @param obj the object to convert to an iterator * @return a suitable iterator, never null */ public static Iterator getIterator(Object obj) { if (obj == null) { return emptyIterator(); } else if (obj instanceof Iterator) { return (Iterator) obj; } else if (obj instanceof Collection) { return ((Collection) obj).iterator(); } else if (obj instanceof Object[]) { return new ObjectArrayIterator((Object[]) obj); } else if (obj instanceof Enumeration) { return new EnumerationIterator((Enumeration) obj); } else if (obj instanceof Map) { return ((Map) obj).values().iterator(); } else if (obj instanceof Dictionary) { return new EnumerationIterator(((Dictionary) obj).elements()); } else if (obj != null && obj.getClass().isArray()) { return new ArrayIterator(obj); } else { try { Method method = obj.getClass().getMethod("iterator", null); if (Iterator.class.isAssignableFrom(method.getReturnType())) { Iterator it = (Iterator) method.invoke(obj, null); if (it != null) { return it; } } } catch (Exception ex) { // ignore } return singletonIterator(obj); } } } collections-generic-4.01/src/java/org/apache/commons/collections15/Unmodifiable.java0000644000175000017500000000260010464140756030721 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15; /** * Marker interface for collections15, maps and iterators that are unmodifiable. *

      * This interface enables testing such as: *

       * if (coll instanceof Unmodifiable) {
       *   coll = new ArrayList(coll);
       * }
       * // now we know coll is modifiable
       * 
      * Of course all this only works if you use the Unmodifiable classes defined * in this library. If you use the JDK unmodifiable class via java util Collections * then the interface won't be there. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:19 $ * @since Commons Collections 3.0 */ public interface Unmodifiable { // marker interface - no methods to implement } collections-generic-4.01/src/java/org/apache/commons/collections15/BoundedMap.java0000644000175000017500000000275310464140760030345 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15; import java.util.Map; /** * Defines a map that is bounded in size. *

      * The size of the map can vary, but it can never exceed a preset * maximum number of elements. This interface allows the querying of details * associated with the maximum number of elements. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:19 $ * @since Commons Collections 3.0 */ public interface BoundedMap extends Map { /** * Returns true if this map is full and no new elements can be added. * * @return true if the map is full */ boolean isFull(); /** * Gets the maximum size of the map (the bound). * * @return the maximum number of elements the map can hold */ int maxSize(); } collections-generic-4.01/src/java/org/apache/commons/collections15/collection/0000755000175000017500000000000011664401370027610 5ustar giovannigiovanni././@LongLink0000000000000000000000000000015700000000000011570 Lustar rootrootcollections-generic-4.01/src/java/org/apache/commons/collections15/collection/AbstractCollectionDecorator.javacollections-generic-4.01/src/java/org/apache/commons/collections15/collection/AbstractCollectionDeco0000644000175000017500000001027010464140755034111 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.collection; import java.util.Collection; import java.util.Iterator; /** * Decorates another Collection to provide additional behaviour. *

      * Each method call made on this Collection is forwarded to the * decorated Collection. This class is used as a framework on which * to build to extensions such as synchronized and unmodifiable behaviour. The * main advantage of decoration is that one decorator can wrap any implementation * of Collection, whereas sub-classing requires a new class to be * written for each implementation. *

      * This implementation does not perform any special processing with * {@link #iterator()}. Instead it simply returns the value from the * wrapped collection. This may be undesirable, for example if you are trying * to write an unmodifiable implementation it might provide a loophole. * * @author Stephen Colebourne * @author Matt Hall, John Watkinson, Paul Jack * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:20 $ * @since Commons Collections 3.0 */ public abstract class AbstractCollectionDecorator implements Collection { /** * The collection being decorated */ protected Collection collection; /** * Constructor only used in deserialization, do not use otherwise. * * @since Commons Collections 3.1 */ protected AbstractCollectionDecorator() { super(); } /** * Constructor that wraps (not copies). * * @param coll the collection to decorate, must not be null * @throws IllegalArgumentException if the collection is null */ protected AbstractCollectionDecorator(Collection coll) { if (coll == null) { throw new IllegalArgumentException("Collection must not be null"); } this.collection = coll; } /** * Gets the collection being decorated. * * @return the decorated collection */ protected Collection getCollection() { return collection; } //----------------------------------------------------------------------- public boolean add(E object) { return collection.add(object); } public boolean addAll(Collection coll) { return collection.addAll(coll); } public void clear() { collection.clear(); } public boolean contains(Object object) { return collection.contains(object); } public boolean isEmpty() { return collection.isEmpty(); } public Iterator iterator() { return collection.iterator(); } public boolean remove(Object object) { return collection.remove(object); } public int size() { return collection.size(); } public Object[] toArray() { return (Object[]) collection.toArray(); } public T[] toArray(T[] object) { return (T[]) collection.toArray(object); } public boolean containsAll(Collection coll) { return collection.containsAll(coll); } public boolean removeAll(Collection coll) { return collection.removeAll(coll); } public boolean retainAll(Collection coll) { return collection.retainAll(coll); } public boolean equals(Object object) { if (object == this) { return true; } return collection.equals(object); } public int hashCode() { return collection.hashCode(); } public String toString() { return collection.toString(); } } ././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootcollections-generic-4.01/src/java/org/apache/commons/collections15/collection/UnmodifiableCollection.javacollections-generic-4.01/src/java/org/apache/commons/collections15/collection/UnmodifiableCollection0000644000175000017500000000612110464140762034147 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.collection; import org.apache.commons.collections15.Unmodifiable; import org.apache.commons.collections15.iterators.UnmodifiableIterator; import java.util.Collection; import java.util.Iterator; /** * Decorates another Collection to ensure it can't be altered. *

      * This class is Serializable from Commons Collections 3.1. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:20 $ * @since Commons Collections 3.0 */ public final class UnmodifiableCollection extends AbstractSerializableCollectionDecorator implements Unmodifiable { /** * Serialization version */ private static final long serialVersionUID = -239892006883819945L; /** * Factory method to create an unmodifiable collection. *

      * If the collection passed in is already unmodifiable, it is returned. * * @param coll the collection to decorate, must not be null * @return an unmodifiable collection * @throws IllegalArgumentException if collection is null */ public static Collection decorate(Collection coll) { if (coll instanceof Unmodifiable) { return coll; } return new UnmodifiableCollection(coll); } //----------------------------------------------------------------------- /** * Constructor that wraps (not copies). * * @param coll the collection to decorate, must not be null * @throws IllegalArgumentException if collection is null */ private UnmodifiableCollection(Collection coll) { super(coll); } //----------------------------------------------------------------------- public Iterator iterator() { return UnmodifiableIterator.decorate(getCollection().iterator()); } public boolean add(E object) { throw new UnsupportedOperationException(); } public boolean addAll(Collection coll) { throw new UnsupportedOperationException(); } public void clear() { throw new UnsupportedOperationException(); } public boolean remove(Object object) { throw new UnsupportedOperationException(); } public boolean removeAll(Collection coll) { throw new UnsupportedOperationException(); } public boolean retainAll(Collection coll) { throw new UnsupportedOperationException(); } } ././@LongLink0000000000000000000000000000017300000000000011566 Lustar rootrootcollections-generic-4.01/src/java/org/apache/commons/collections15/collection/AbstractSerializableCollectionDecorator.javacollections-generic-4.01/src/java/org/apache/commons/collections15/collection/AbstractSerializableCo0000644000175000017500000000414410464140765034117 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.collection; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.Collection; /** * Serializable subclass of AbstractCollectionDecorator. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @since Commons Collections 3.1 */ public abstract class AbstractSerializableCollectionDecorator extends AbstractCollectionDecorator implements Serializable { /** * Serialization version */ private static final long serialVersionUID = 6249888059822088500L; /** * Constructor. */ protected AbstractSerializableCollectionDecorator(Collection coll) { super(coll); } //----------------------------------------------------------------------- /** * Write the collection out using a custom routine. * * @param out the output stream * @throws IOException */ private void writeObject(ObjectOutputStream out) throws IOException { out.defaultWriteObject(); out.writeObject(collection); } /** * Read the collection in using a custom routine. * * @param in the input stream * @throws IOException * @throws ClassNotFoundException */ private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); collection = (Collection) in.readObject(); } } collections-generic-4.01/src/java/org/apache/commons/collections15/collection/TypedCollection.java0000644000175000017500000000424210464140762033560 0ustar giovannigiovanni// GenericsNote: Not converted, deprecated. /* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.collection; import org.apache.commons.collections15.functors.InstanceofPredicate; import java.util.Collection; /** * Decorates a Collection to validate that elements added are of a specific type. *

      * The validation of additions is performed via an instanceof test against * a specified Class. If an object cannot be added to the * collection, an IllegalArgumentException is thrown. * * @author Stephen Colebourne * @author Matt Hall, John Watkinson, Matthew Hawthorne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:20 $ * @since Commons Collections 3.0 * @deprecated Type safe classes are no longer required under 1.5. */ public class TypedCollection { /** * Factory method to create a typed collection. *

      * If there are any elements already in the collection being decorated, they * are validated. * * @param coll the collection to decorate, must not be null * @param type the type to allow into the collection, must not be null * @return a new typed collection * @throws IllegalArgumentException if collection or type is null * @throws IllegalArgumentException if the collection contains invalid elements */ public static Collection decorate(Collection coll, Class type) { return new PredicatedCollection(coll, InstanceofPredicate.getInstance(type)); } /** * Restrictive constructor. */ protected TypedCollection() { super(); } } ././@LongLink0000000000000000000000000000016100000000000011563 Lustar rootrootcollections-generic-4.01/src/java/org/apache/commons/collections15/collection/UnmodifiableBoundedCollection.javacollections-generic-4.01/src/java/org/apache/commons/collections15/collection/UnmodifiableBoundedCol0000644000175000017500000001171510464140756034102 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.collection; import org.apache.commons.collections15.BoundedCollection; import org.apache.commons.collections15.iterators.UnmodifiableIterator; import java.util.Collection; import java.util.Iterator; /** * UnmodifiableBoundedCollection decorates another * BoundedCollection to ensure it can't be altered. *

      * If a BoundedCollection is first wrapped in some other collection decorator, * such as synchronized or predicated, the BoundedCollection methods are no * longer accessible. * The factory on this class will attempt to retrieve the bounded nature by * examining the package scope variables. *

      * This class is Serializable from Commons Collections 3.1. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:20 $ * @since Commons Collections 3.0 */ public final class UnmodifiableBoundedCollection extends AbstractSerializableCollectionDecorator implements BoundedCollection { /** * Serialization version */ private static final long serialVersionUID = -7112672385450340330L; /** * Factory method to create an unmodifiable bounded collection. * * @param coll the BoundedCollection to decorate, must not be null * @return a new unmodifiable bounded collection * @throws IllegalArgumentException if bag is null */ public static BoundedCollection decorate(BoundedCollection coll) { return new UnmodifiableBoundedCollection(coll); } /** * Factory method to create an unmodifiable bounded collection. *

      * This method is capable of drilling down through up to 1000 other decorators * to find a suitable BoundedCollection. * * @param coll the BoundedCollection to decorate, must not be null * @return a new unmodifiable bounded collection * @throws IllegalArgumentException if bag is null */ public static BoundedCollection decorateUsing(Collection coll) { if (coll == null) { throw new IllegalArgumentException("The collection must not be null"); } // handle decorators for (int i = 0; i < 1000; i++) { // counter to prevent infinite looping if (coll instanceof BoundedCollection) { break; // normal loop exit } else if (coll instanceof AbstractCollectionDecorator) { coll = ((AbstractCollectionDecorator) coll).collection; } else if (coll instanceof SynchronizedCollection) { coll = ((SynchronizedCollection) coll).collection; } else { break; // normal loop exit } } if (coll instanceof BoundedCollection == false) { throw new IllegalArgumentException("The collection is not a bounded collection"); } return new UnmodifiableBoundedCollection((BoundedCollection) coll); } /** * Constructor that wraps (not copies). * * @param coll the collection to decorate, must not be null * @throws IllegalArgumentException if coll is null */ private UnmodifiableBoundedCollection(BoundedCollection coll) { super(coll); } //----------------------------------------------------------------------- public Iterator iterator() { return UnmodifiableIterator.decorate(getCollection().iterator()); } public boolean add(E object) { throw new UnsupportedOperationException(); } public boolean addAll(Collection coll) { throw new UnsupportedOperationException(); } public void clear() { throw new UnsupportedOperationException(); } public boolean remove(Object object) { throw new UnsupportedOperationException(); } public boolean removeAll(Collection coll) { throw new UnsupportedOperationException(); } public boolean retainAll(Collection coll) { throw new UnsupportedOperationException(); } //----------------------------------------------------------------------- public boolean isFull() { return ((BoundedCollection) collection).isFull(); } public int maxSize() { return ((BoundedCollection) collection).maxSize(); } } ././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootcollections-generic-4.01/src/java/org/apache/commons/collections15/collection/SynchronizedCollection.javacollections-generic-4.01/src/java/org/apache/commons/collections15/collection/SynchronizedCollection0000644000175000017500000001301010464140754034224 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.collection; import java.io.Serializable; import java.util.Collection; import java.util.Iterator; /** * Decorates another Collection to synchronize its behaviour * for a multi-threaded environment. *

      * Iterators must be manually synchronized: *

       * synchronized (coll) {
       *   Iterator it = coll.iterator();
       *   // do stuff with iterator
       * }
       * 
      *

      * This class is Serializable from Commons Collections 3.1. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:20 $ * @since Commons Collections 3.0 */ public class SynchronizedCollection implements Collection, Serializable { /** * Serialization version */ private static final long serialVersionUID = 2412805092710877986L; /** * The collection to decorate */ protected final Collection collection; /** * The object to lock on, needed for List/SortedSet views */ protected final Object lock; /** * Factory method to create a synchronized collection. * * @param coll the collection to decorate, must not be null * @return a new synchronized collection * @throws IllegalArgumentException if collection is null */ public static Collection decorate(Collection coll) { return new SynchronizedCollection(coll); } //----------------------------------------------------------------------- /** * Constructor that wraps (not copies). * * @param collection the collection to decorate, must not be null * @throws IllegalArgumentException if the collection is null */ protected SynchronizedCollection(Collection collection) { if (collection == null) { throw new IllegalArgumentException("Collection must not be null"); } this.collection = collection; this.lock = this; } /** * Constructor that wraps (not copies). * * @param collection the collection to decorate, must not be null * @param lock the lock object to use, must not be null * @throws IllegalArgumentException if the collection is null */ protected SynchronizedCollection(Collection collection, Object lock) { if (collection == null) { throw new IllegalArgumentException("Collection must not be null"); } this.collection = collection; this.lock = lock; } //----------------------------------------------------------------------- public boolean add(E object) { synchronized (lock) { return collection.add(object); } } public boolean addAll(Collection coll) { synchronized (lock) { return collection.addAll(coll); } } public void clear() { synchronized (lock) { collection.clear(); } } public boolean contains(Object object) { synchronized (lock) { return collection.contains(object); } } public boolean containsAll(Collection coll) { synchronized (lock) { return collection.containsAll(coll); } } public boolean isEmpty() { synchronized (lock) { return collection.isEmpty(); } } /** * Iterators must be manually synchronized. *

           * synchronized (coll) {
           *   Iterator it = coll.iterator();
           *   // do stuff with iterator
           * }
           *
           * @return an iterator that must be manually synchronized on the collection
           */
          public Iterator iterator() {
              return collection.iterator();
          }
      
          public Object[] toArray() {
              synchronized (lock) {
                  return collection.toArray();
              }
          }
      
          public  T[] toArray(T[] object) {
              synchronized (lock) {
                  return collection.toArray(object);
              }
          }
      
          public boolean remove(Object object) {
              synchronized (lock) {
                  return collection.remove(object);
              }
          }
      
          public boolean removeAll(Collection coll) {
              synchronized (lock) {
                  return collection.removeAll(coll);
              }
          }
      
          public boolean retainAll(Collection coll) {
              synchronized (lock) {
                  return collection.retainAll(coll);
              }
          }
      
          public int size() {
              synchronized (lock) {
                  return collection.size();
              }
          }
      
          public boolean equals(Object object) {
              synchronized (lock) {
                  if (object == this) {
                      return true;
                  }
                  return collection.equals(object);
              }
          }
      
          public int hashCode() {
              synchronized (lock) {
                  return collection.hashCode();
              }
          }
      
          public String toString() {
              synchronized (lock) {
                  return collection.toString();
              }
          }
      
      }
      ././@LongLink0000000000000000000000000000014700000000000011567 Lustar  rootrootcollections-generic-4.01/src/java/org/apache/commons/collections15/collection/CompositeCollection.javacollections-generic-4.01/src/java/org/apache/commons/collections15/collection/CompositeCollection.ja0000644000175000017500000003772510464140764034124 0ustar  giovannigiovanni// GenericsNote: Converted.
      /*
       *  Copyright 2001-2004 The Apache Software Foundation
       *
       *  Licensed under the Apache License, Version 2.0 (the "License");
       *  you may not use this file except in compliance with the License.
       *  You may obtain a copy of the License at
       *
       *      http://www.apache.org/licenses/LICENSE-2.0
       *
       *  Unless required by applicable law or agreed to in writing, software
       *  distributed under the License is distributed on an "AS IS" BASIS,
       *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
       *  See the License for the specific language governing permissions and
       *  limitations under the License.
       */
      package org.apache.commons.collections15.collection;
      
      import org.apache.commons.collections15.iterators.EmptyIterator;
      import org.apache.commons.collections15.iterators.IteratorChain;
      import org.apache.commons.collections15.list.UnmodifiableList;
      
      import java.lang.reflect.Array;
      import java.util.ArrayList;
      import java.util.Arrays;
      import java.util.Collection;
      import java.util.Iterator;
      
      /**
       * Decorates a collection of other collections15 to provide a single unified view.
       * 

      * Changes made to this collection will actually be made on the decorated collection. * Add and remove operations require the use of a pluggable strategy. If no * strategy is provided then add and remove are unsupported. * * @author Brian McCallister * @author Stephen Colebourne * @author Matt Hall, John Watkinson, Phil Steitz * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:20 $ * @since Commons Collections 3.0 */ public class CompositeCollection implements Collection { /** * CollectionMutator to handle changes to the collection */ protected CollectionMutator mutator; /** * Collections in the composite */ protected Collection[] all; /** * Create an empty CompositeCollection. */ public CompositeCollection() { super(); this.all = new Collection[0]; } /** * Create a Composite Collection with only coll composited. * * @param coll a collection to decorate */ public CompositeCollection(Collection coll) { this(); this.addComposited(coll); } /** * Create a CompositeCollection with colls as the initial list of * composited collections15. * * @param colls a variable number of collections15 to decorate */ public CompositeCollection(Collection... colls) { this(); this.addComposited(colls); } //----------------------------------------------------------------------- /** * Gets the size of this composite collection. *

      * This implementation calls size() on each collection. * * @return total number of elements in all contained containers */ public int size() { int size = 0; for (int i = this.all.length - 1; i >= 0; i--) { size += this.all[i].size(); } return size; } /** * Checks whether this composite collection is empty. *

      * This implementation calls isEmpty() on each collection. * * @return true if all of the contained collections15 are empty */ public boolean isEmpty() { for (int i = this.all.length - 1; i >= 0; i--) { if (this.all[i].isEmpty() == false) { return false; } } return true; } /** * Checks whether this composite collection contains the object. *

      * This implementation calls contains() on each collection. * * @param obj the object to search for * @return true if obj is contained in any of the contained collections15 */ public boolean contains(Object obj) { for (int i = this.all.length - 1; i >= 0; i--) { if (this.all[i].contains(obj)) { return true; } } return false; } /** * Gets an iterator over all the collections15 in this composite. *

      * This implementation uses an IteratorChain. * * @return an IteratorChain instance which supports * remove(). Iteration occurs over contained collections15 in * the order they were added, but this behavior should not be relied upon. * @see IteratorChain */ public Iterator iterator() { if (this.all.length == 0) { return EmptyIterator.INSTANCE; } IteratorChain chain = new IteratorChain(); for (int i = 0; i < this.all.length; ++i) { chain.addIterator(this.all[i].iterator()); } return chain; } /** * Returns an array containing all of the elements in this composite. * * @return an object array of all the elements in the collection */ public E[] toArray() { final E[] result = (E[]) new Object[this.size()]; int i = 0; for (Iterator it = this.iterator(); it.hasNext(); i++) { result[i] = (E) it.next(); } return result; } /** * Returns an object array, populating the supplied array if possible. * See Collection interface for full details. * * @param array the array to use, populating if possible * @return an array of all the elements in the collection */ public E[] toArray(E[] array) { int size = this.size(); E[] result = null; if (array.length >= size) { result = array; } else { result = (E[]) Array.newInstance(array.getClass().getComponentType(), size); } int offset = 0; for (int i = 0; i < this.all.length; ++i) { for (Iterator it = this.all[i].iterator(); it.hasNext();) { result[offset++] = (E) it.next(); } } if (result.length > size) { result[size] = null; } return result; } /** * Adds an object to the collection, throwing UnsupportedOperationException * unless a CollectionMutator strategy is specified. * * @param obj the object to add * @return true if the collection was modified * @throws UnsupportedOperationException if CollectionMutator hasn't been set * @throws UnsupportedOperationException if add is unsupported * @throws ClassCastException if the object cannot be added due to its type * @throws NullPointerException if the object cannot be added because its null * @throws IllegalArgumentException if the object cannot be added */ public boolean add(E obj) { if (this.mutator == null) { throw new UnsupportedOperationException("add() is not supported on CompositeCollection without a CollectionMutator strategy"); } return this.mutator.add(this, this.all, obj); } /** * Removes an object from the collection, throwing UnsupportedOperationException * unless a CollectionMutator strategy is specified. * * @param obj the object being removed * @return true if the collection is changed * @throws UnsupportedOperationException if removed is unsupported * @throws ClassCastException if the object cannot be removed due to its type * @throws NullPointerException if the object cannot be removed because its null * @throws IllegalArgumentException if the object cannot be removed */ public boolean remove(Object obj) { if (this.mutator == null) { throw new UnsupportedOperationException("remove() is not supported on CompositeCollection without a CollectionMutator strategy"); } return this.mutator.remove(this, this.all, obj); } /** * Checks whether this composite contains all the elements in the specified collection. *

      * This implementation calls contains() for each element in the * specified collection. * * @param coll the collection to check for * @return true if all elements contained */ public boolean containsAll(Collection coll) { for (Iterator it = coll.iterator(); it.hasNext();) { if (this.contains(it.next()) == false) { return false; } } return true; } /** * Adds a collection of elements to this collection, throwing * UnsupportedOperationException unless a CollectionMutator strategy is specified. * * @param coll the collection to add * @return true if the collection was modified * @throws UnsupportedOperationException if CollectionMutator hasn't been set * @throws UnsupportedOperationException if add is unsupported * @throws ClassCastException if the object cannot be added due to its type * @throws NullPointerException if the object cannot be added because its null * @throws IllegalArgumentException if the object cannot be added */ public boolean addAll(Collection coll) { if (this.mutator == null) { throw new UnsupportedOperationException("addAll() is not supported on CompositeCollection without a CollectionMutator strategy"); } return this.mutator.addAll(this, this.all, coll); } /** * Removes the elements in the specified collection from this composite collection. *

      * This implementation calls removeAll on each collection. * * @param coll the collection to remove * @return true if the collection was modified * @throws UnsupportedOperationException if removeAll is unsupported */ public boolean removeAll(Collection coll) { if (coll.size() == 0) { return false; } boolean changed = false; for (int i = this.all.length - 1; i >= 0; i--) { changed = (this.all[i].removeAll(coll) || changed); } return changed; } /** * Retains all the elements in the specified collection in this composite collection, * removing all others. *

      * This implementation calls retainAll() on each collection. * * @param coll the collection to remove * @return true if the collection was modified * @throws UnsupportedOperationException if retainAll is unsupported */ public boolean retainAll(final Collection coll) { boolean changed = false; for (int i = this.all.length - 1; i >= 0; i--) { changed = (this.all[i].retainAll(coll) || changed); } return changed; } /** * Removes all of the elements from this collection . *

      * This implementation calls clear() on each collection. * * @throws UnsupportedOperationException if clear is unsupported */ public void clear() { for (int i = 0; i < this.all.length; ++i) { this.all[i].clear(); } } //----------------------------------------------------------------------- /** * Specify a CollectionMutator strategy instance to handle changes. * * @param mutator the mutator to use */ public void setMutator(CollectionMutator mutator) { this.mutator = mutator; } /** * Add these Collections to the list of collections15 in this composite * * @param comps Collections to be appended to the composite */ public void addComposited(Collection... comps) { ArrayList list = new ArrayList(Arrays.asList(this.all)); list.addAll(Arrays.asList(comps)); all = (Collection[]) list.toArray(new Collection[list.size()]); } /** * Add an additional collection to this composite. * * @param c the collection to add */ public void addComposited(Collection c) { this.addComposited(new Collection[]{c}); } /** * Add two additional collections15 to this composite. * * @deprecated Superceded by the variable argument implementation of addComposited() * @param c the first collection to add * @param d the second collection to add */ public void addComposited(Collection c, Collection d) { this.addComposited(new Collection[]{c, d}); } /** * Removes a collection from the those being decorated in this composite. * * @param coll collection to be removed */ public void removeComposited(Collection coll) { ArrayList list = new ArrayList(this.all.length); list.addAll(Arrays.asList(this.all)); list.remove(coll); this.all = (Collection[]) list.toArray(new Collection[list.size()]); } /** * Returns a new collection containing all of the elements * * @return A new ArrayList containing all of the elements in this composite. * The new collection is not backed by this composite. */ public Collection toCollection() { return new ArrayList(this); } /** * Gets the collections15 being decorated. * * @return Unmodifiable collection of all collections15 in this composite. */ public Collection> getCollections() { return UnmodifiableList.decorate(Arrays.asList(this.all)); } //----------------------------------------------------------------------- /** * Pluggable strategy to handle changes to the composite. */ public interface CollectionMutator { /** * Called when an object is to be added to the composite. * * @param composite the CompositeCollection being changed * @param collections all of the Collection instances in this CompositeCollection * @param obj the object being added * @return true if the collection is changed * @throws UnsupportedOperationException if add is unsupported * @throws ClassCastException if the object cannot be added due to its type * @throws NullPointerException if the object cannot be added because its null * @throws IllegalArgumentException if the object cannot be added */ public boolean add(CompositeCollection composite, Collection[] collections, Object obj); /** * Called when a collection is to be added to the composite. * * @param composite the CompositeCollection being changed * @param collections all of the Collection instances in this CompositeCollection * @param coll the collection being added * @return true if the collection is changed * @throws UnsupportedOperationException if add is unsupported * @throws ClassCastException if the object cannot be added due to its type * @throws NullPointerException if the object cannot be added because its null * @throws IllegalArgumentException if the object cannot be added */ public boolean addAll(CompositeCollection composite, Collection[] collections, Collection coll); /** * Called when an object is to be removed to the composite. * * @param composite the CompositeCollection being changed * @param collections all of the Collection instances in this CompositeCollection * @param obj the object being removed * @return true if the collection is changed * @throws UnsupportedOperationException if removed is unsupported * @throws ClassCastException if the object cannot be removed due to its type * @throws NullPointerException if the object cannot be removed because its null * @throws IllegalArgumentException if the object cannot be removed */ public boolean remove(CompositeCollection composite, Collection[] collections, Object obj); } } ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootcollections-generic-4.01/src/java/org/apache/commons/collections15/collection/TransformedCollection.javacollections-generic-4.01/src/java/org/apache/commons/collections15/collection/TransformedCollection.0000644000175000017500000001161710464140755034123 0ustar giovannigiovanni// GenericsNote: Converted, but unfortunately very little type-safety could be achieved without breaking Collection interface. /* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.collection; import org.apache.commons.collections15.Transformer; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; /** * Decorates another Collection to transform objects that are added. *

      * The add methods are affected by this class. * Thus objects must be removed or searched for using their transformed form. * For example, if the transformation converts Strings to Integers, you must * use the Integer form to remove objects. *

      * This class is Serializable from Commons Collections 3.1. *

      * Note: This class cannot support generics without breaking the Collection contract. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:20 $ * @since Commons Collections 3.0 */ public class TransformedCollection extends AbstractSerializableCollectionDecorator { /** * Serialization version */ private static final long serialVersionUID = 8692300188161871514L; /** * The transformer to use */ protected final Transformer transformer; /** * Factory method to create a transforming collection. *

      * If there are any elements already in the collection being decorated, they * are NOT transformed. * * @param coll the collection to decorate, must not be null * @param transformer the transformer to use for conversion, must not be null * @return a new transformed collection * @throws IllegalArgumentException if collection or transformer is null */ public static Collection decorate(Collection coll, Transformer transformer) { return new TransformedCollection(coll, transformer); } //----------------------------------------------------------------------- /** * Constructor that wraps (not copies). *

      * If there are any elements already in the collection being decorated, they * are NOT transformed. * * @param coll the collection to decorate, must not be null * @param transformer the transformer to use for conversion, must not be null * @throws IllegalArgumentException if collection or transformer is null */ protected TransformedCollection(Collection coll, Transformer transformer) { super(coll); if (transformer == null) { throw new IllegalArgumentException("Transformer must not be null"); } this.transformer = transformer; } /** * Transforms an object. *

      * The transformer itself may throw an exception if necessary. * * @param object the object to transform * @return a transformed object */ protected O transform(I object) { return transformer.transform(object); } /** * Transforms a collection. *

      * The transformer itself may throw an exception if necessary. * * @param coll the collection to transform * @return a transformed object */ protected Collection transform(Collection coll) { List list = new ArrayList(coll.size()); for (Iterator it = coll.iterator(); it.hasNext();) { list.add(transform(it.next())); } return list; } //----------------------------------------------------------------------- public boolean add(Object object) { O transformed = transform((I) object); return getCollection().add(transformed); } /** * A better typed version of the add method (although breaks the Collection interface). */ public boolean addTyped(I object) { return add(object); } public boolean addAll(Collection coll) { Collection col2 = transform((Collection) coll); return getCollection().addAll(col2); } /** * A better typed version of the addAll method (although breaks the Collection interface). */ public boolean addAllTyped(Collection coll) { return addAll(coll); } } collections-generic-4.01/src/java/org/apache/commons/collections15/collection/package.html0000644000175000017500000000257010464140755032101 0ustar giovannigiovanni

      This package contains implementations of the {@link java.util.Collection Collection} interface.

      The following implementations are provided in the package:

      • CompositeCollection - a collection that combines multiple collections into one
      The following decorators are provided in the package:
      • Synchronized - synchronizes method access for multi-threaded environments
      • Unmodifiable - ensures the collection cannot be altered
      • Predicated - ensures that only elements that are valid according to a predicate can be added
      • Typed - ensures that only elements that are of a specific type can be added
      • Transformed - transforms elements as they are added
      ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootcollections-generic-4.01/src/java/org/apache/commons/collections15/collection/PredicatedCollection.javacollections-generic-4.01/src/java/org/apache/commons/collections15/collection/PredicatedCollection.j0000644000175000017500000001214310464140760034044 0ustar giovannigiovanni// GenericsNotes: Converted. /* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.collection; import org.apache.commons.collections15.Predicate; import java.util.Collection; import java.util.Iterator; /** * Decorates another Collection to validate that additions * match a specified predicate. *

      * This collection exists to provide validation for the decorated collection. * It is normally created to decorate an empty collection. * If an object cannot be added to the collection, an IllegalArgumentException is thrown. *

      * One usage would be to ensure that no null entries are added to the collection. *

      Collection coll = PredicatedCollection.decorate(new ArrayList(), NotNullPredicate.INSTANCE);
      *

      * This class is Serializable from Commons Collections 3.1. * * @author Stephen Colebourne * @author Matt Hall, John Watkinson, Paul Jack * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:20 $ * @since Commons Collections 3.0 */ public class PredicatedCollection extends AbstractSerializableCollectionDecorator { /** * Serialization version */ private static final long serialVersionUID = -5259182142076705162L; /** * The predicate to use */ protected final Predicate predicate; /** * Factory method to create a predicated (validating) collection. *

      * If there are any elements already in the collection being decorated, they * are validated. * * @param coll the collection to decorate, must not be null * @param predicate the predicate to use for validation, must not be null * @return a new predicated collection * @throws IllegalArgumentException if collection or predicate is null * @throws IllegalArgumentException if the collection contains invalid elements */ public static Collection decorate(Collection coll, Predicate predicate) { return new PredicatedCollection(coll, predicate); } //----------------------------------------------------------------------- /** * Constructor that wraps (not copies). *

      * If there are any elements already in the collection being decorated, they * are validated. * * @param coll the collection to decorate, must not be null * @param predicate the predicate to use for validation, must not be null * @throws IllegalArgumentException if collection or predicate is null * @throws IllegalArgumentException if the collection contains invalid elements */ protected PredicatedCollection(Collection coll, Predicate predicate) { super(coll); if (predicate == null) { throw new IllegalArgumentException("Predicate must not be null"); } this.predicate = predicate; for (Iterator it = coll.iterator(); it.hasNext();) { validate(it.next()); } } /** * Validates the object being added to ensure it matches the predicate. *

      * The predicate itself should not throw an exception, but return false to * indicate that the object cannot be added. * * @param object the object being added * @throws IllegalArgumentException if the add is invalid */ protected void validate(E object) { if (predicate.evaluate(object) == false) { throw new IllegalArgumentException("Cannot add Object '" + object + "' - Predicate rejected it"); } } //----------------------------------------------------------------------- /** * Override to validate the object being added to ensure it matches * the predicate. * * @param object the object being added * @return the result of adding to the underlying collection * @throws IllegalArgumentException if the add is invalid */ public boolean add(E object) { validate(object); return getCollection().add(object); } /** * Override to validate the objects being added to ensure they match * the predicate. If any one fails, no update is made to the underlying * collection. * * @param coll the collection being added * @return the result of adding to the underlying collection * @throws IllegalArgumentException if the add is invalid */ public boolean addAll(Collection coll) { for (Iterator it = coll.iterator(); it.hasNext();) { validate(it.next()); } return getCollection().addAll(coll); } } collections-generic-4.01/src/java/org/apache/commons/collections15/MapUtils.java0000644000175000017500000014717310464140760030073 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15; import org.apache.commons.collections15.map.*; import java.io.PrintStream; import java.text.NumberFormat; import java.text.ParseException; import java.util.*; /** * Provides utility methods and decorators for * {@link Map} and {@link SortedMap} instances. *

      * It contains various type safe methods * as well as other useful features like deep copying. *

      * It also provides the following decorators: *

      *

        *
      • {@link #fixedSizeMap(Map)} *
      • {@link #fixedSizeSortedMap(SortedMap)} *
      • {@link #lazyMap(Map,Factory)} *
      • {@link #lazySortedMap(SortedMap,Factory)} *
      • {@link #predicatedMap(Map,Predicate,Predicate)} *
      • {@link #predicatedSortedMap(SortedMap,Predicate,Predicate)} *
      • {@link #transformedMap(Map, Transformer, Transformer)} *
      • {@link #transformedSortedMap(SortedMap, Transformer, Transformer)} *
      • {@link #typedMap(Map, Class, Class)} *
      • {@link #typedSortedMap(SortedMap, Class, Class)} *
      * * @author James Strachan * @author Nissim Karpenstein * @author Kasper Nielsen * @author Paul Jack * @author Stephen Colebourne * @author Matthew Hawthorne * @author Arun Mammen Thomas * @author Janek Bogucki * @author Max Rydahl Andersen * @author Matt Hall, John Watkinson, Ashwin S * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:19 $ * @since Commons Collections 1.0 */ public class MapUtils { /** * An empty unmodifiable map. * This was not provided in JDK1.2. */ public static final Map EMPTY_MAP = UnmodifiableMap.decorate(new HashMap(1)); /** * An empty unmodifiable sorted map. * This is not provided in the JDK. */ public static final SortedMap EMPTY_SORTED_MAP = UnmodifiableSortedMap.decorate(new TreeMap()); /** * String used to indent the verbose and debug Map prints. */ private static final String INDENT_STRING = " "; /** * MapUtils should not normally be instantiated. */ public MapUtils() { } // Type safe getters //------------------------------------------------------------------------- /** * Gets from a Map in a null-safe manner. * * @param map the map to use * @param key the key to look up * @return the value in the Map, null if null map input */ public static V getObject(final Map map, final K key) { if (map != null) { return map.get(key); } return null; } /** * Gets a String from a Map in a null-safe manner. *

      * The String is obtained via toString. * * @param map the map to use * @param key the key to look up * @return the value in the Map as a String, null if null map input */ public static String getString(final Map map, final K key) { if (map != null) { V answer = map.get(key); if (answer != null) { return answer.toString(); } } return null; } /** * Gets a Boolean from a Map in a null-safe manner. *

      * If the value is a Boolean it is returned directly. * If the value is a String and it equals 'true' ignoring case * then true is returned, otherwise false. * If the value is a Number an integer zero value returns * false and non-zero returns true. * Otherwise, null is returned. * * @param map the map to use * @param key the key to look up * @return the value in the Map as a Boolean, null if null map input */ public static Boolean getBoolean(final Map map, final Object key) { if (map != null) { Object answer = map.get(key); if (answer != null) { if (answer instanceof Boolean) { return (Boolean) answer; } else if (answer instanceof String) { return new Boolean((String) answer); } else if (answer instanceof Number) { Number n = (Number) answer; return (n.intValue() != 0) ? Boolean.TRUE : Boolean.FALSE; } } } return null; } /** * Gets a Number from a Map in a null-safe manner. *

      * If the value is a Number it is returned directly. * If the value is a String it is converted using * {@link NumberFormat#parse(String)} on the system default formatter * returning null if the conversion fails. * Otherwise, null is returned. * * @param map the map to use * @param key the key to look up * @return the value in the Map as a Number, null if null map input */ public static Number getNumber(final Map map, final Object key) { if (map != null) { Object answer = map.get(key); if (answer != null) { if (answer instanceof Number) { return (Number) answer; } else if (answer instanceof String) { try { String text = (String) answer; return NumberFormat.getInstance().parse(text); } catch (ParseException e) { logInfo(e); } } } } return null; } /** * Gets a Byte from a Map in a null-safe manner. *

      * The Byte is obtained from the results of {@link #getNumber(Map,Object)}. * * @param map the map to use * @param key the key to look up * @return the value in the Map as a Byte, null if null map input */ public static Byte getByte(final Map map, final Object key) { Number answer = getNumber(map, key); if (answer == null) { return null; } else if (answer instanceof Byte) { return (Byte) answer; } return new Byte(answer.byteValue()); } /** * Gets a Short from a Map in a null-safe manner. *

      * The Short is obtained from the results of {@link #getNumber(Map,Object)}. * * @param map the map to use * @param key the key to look up * @return the value in the Map as a Short, null if null map input */ public static Short getShort(final Map map, final Object key) { Number answer = getNumber(map, key); if (answer == null) { return null; } else if (answer instanceof Short) { return (Short) answer; } return new Short(answer.shortValue()); } /** * Gets a Integer from a Map in a null-safe manner. *

      * The Integer is obtained from the results of {@link #getNumber(Map,Object)}. * * @param map the map to use * @param key the key to look up * @return the value in the Map as a Integer, null if null map input */ public static Integer getInteger(final Map map, final Object key) { Number answer = getNumber(map, key); if (answer == null) { return null; } else if (answer instanceof Integer) { return (Integer) answer; } return new Integer(answer.intValue()); } /** * Gets a Long from a Map in a null-safe manner. *

      * The Long is obtained from the results of {@link #getNumber(Map,Object)}. * * @param map the map to use * @param key the key to look up * @return the value in the Map as a Long, null if null map input */ public static Long getLong(final Map map, final Object key) { Number answer = getNumber(map, key); if (answer == null) { return null; } else if (answer instanceof Long) { return (Long) answer; } return new Long(answer.longValue()); } /** * Gets a Float from a Map in a null-safe manner. *

      * The Float is obtained from the results of {@link #getNumber(Map,Object)}. * * @param map the map to use * @param key the key to look up * @return the value in the Map as a Float, null if null map input */ public static Float getFloat(final Map map, final Object key) { Number answer = getNumber(map, key); if (answer == null) { return null; } else if (answer instanceof Float) { return (Float) answer; } return new Float(answer.floatValue()); } /** * Gets a Double from a Map in a null-safe manner. *

      * The Double is obtained from the results of {@link #getNumber(Map,Object)}. * * @param map the map to use * @param key the key to look up * @return the value in the Map as a Double, null if null map input */ public static Double getDouble(final Map map, final Object key) { Number answer = getNumber(map, key); if (answer == null) { return null; } else if (answer instanceof Double) { return (Double) answer; } return new Double(answer.doubleValue()); } /** * Gets a Map from a Map in a null-safe manner. *

      * If the value returned from the specified map is not a Map then * null is returned. * * @param map the map to use * @param key the key to look up * @return the value in the Map as a Map, null if null map input */ public static Map getMap(final Map> map, final K key) { if (map != null) { Map answer = map.get(key); if (answer != null) { return answer; } } return null; } // Type safe getters with default values //------------------------------------------------------------------------- /** * Looks up the given key in the given map, converting null into the * given default value. * * @param map the map whose value to look up * @param key the key of the value to look up in that map * @param defaultValue what to return if the value is null * @return the value in the map, or defaultValue if the original value * is null or the map is null */ public static V getObject(Map map, K key, V defaultValue) { if (map != null) { V answer = map.get(key); if (answer != null) { return answer; } } return defaultValue; } /** * Looks up the given key in the given map, converting the result into * a string, using the default value if the the conversion fails. * * @param map the map whose value to look up * @param key the key of the value to look up in that map * @param defaultValue what to return if the value is null or if the * conversion fails * @return the value in the map as a string, or defaultValue if the * original value is null, the map is null or the string conversion * fails */ public static String getString(Map map, Object key, String defaultValue) { String answer = getString(map, key); if (answer == null) { answer = defaultValue; } return answer; } /** * Looks up the given key in the given map, converting the result into * a boolean, using the default value if the the conversion fails. * * @param map the map whose value to look up * @param key the key of the value to look up in that map * @param defaultValue what to return if the value is null or if the * conversion fails * @return the value in the map as a boolean, or defaultValue if the * original value is null, the map is null or the boolean conversion * fails */ public static Boolean getBoolean(Map map, Object key, Boolean defaultValue) { Boolean answer = getBoolean(map, key); if (answer == null) { answer = defaultValue; } return answer; } /** * Looks up the given key in the given map, converting the result into * a number, using the default value if the the conversion fails. * * @param map the map whose value to look up * @param key the key of the value to look up in that map * @param defaultValue what to return if the value is null or if the * conversion fails * @return the value in the map as a number, or defaultValue if the * original value is null, the map is null or the number conversion * fails */ public static Number getNumber(Map map, Object key, Number defaultValue) { Number answer = getNumber(map, key); if (answer == null) { answer = defaultValue; } return answer; } /** * Looks up the given key in the given map, converting the result into * a byte, using the default value if the the conversion fails. * * @param map the map whose value to look up * @param key the key of the value to look up in that map * @param defaultValue what to return if the value is null or if the * conversion fails * @return the value in the map as a number, or defaultValue if the * original value is null, the map is null or the number conversion * fails */ public static Byte getByte(Map map, Object key, Byte defaultValue) { Byte answer = getByte(map, key); if (answer == null) { answer = defaultValue; } return answer; } /** * Looks up the given key in the given map, converting the result into * a short, using the default value if the the conversion fails. * * @param map the map whose value to look up * @param key the key of the value to look up in that map * @param defaultValue what to return if the value is null or if the * conversion fails * @return the value in the map as a number, or defaultValue if the * original value is null, the map is null or the number conversion * fails */ public static Short getShort(Map map, Object key, Short defaultValue) { Short answer = getShort(map, key); if (answer == null) { answer = defaultValue; } return answer; } /** * Looks up the given key in the given map, converting the result into * an integer, using the default value if the the conversion fails. * * @param map the map whose value to look up * @param key the key of the value to look up in that map * @param defaultValue what to return if the value is null or if the * conversion fails * @return the value in the map as a number, or defaultValue if the * original value is null, the map is null or the number conversion * fails */ public static Integer getInteger(Map map, Object key, Integer defaultValue) { Integer answer = getInteger(map, key); if (answer == null) { answer = defaultValue; } return answer; } /** * Looks up the given key in the given map, converting the result into * a long, using the default value if the the conversion fails. * * @param map the map whose value to look up * @param key the key of the value to look up in that map * @param defaultValue what to return if the value is null or if the * conversion fails * @return the value in the map as a number, or defaultValue if the * original value is null, the map is null or the number conversion * fails */ public static Long getLong(Map map, Object key, Long defaultValue) { Long answer = getLong(map, key); if (answer == null) { answer = defaultValue; } return answer; } /** * Looks up the given key in the given map, converting the result into * a float, using the default value if the the conversion fails. * * @param map the map whose value to look up * @param key the key of the value to look up in that map * @param defaultValue what to return if the value is null or if the * conversion fails * @return the value in the map as a number, or defaultValue if the * original value is null, the map is null or the number conversion * fails */ public static Float getFloat(Map map, Object key, Float defaultValue) { Float answer = getFloat(map, key); if (answer == null) { answer = defaultValue; } return answer; } /** * Looks up the given key in the given map, converting the result into * a double, using the default value if the the conversion fails. * * @param map the map whose value to look up * @param key the key of the value to look up in that map * @param defaultValue what to return if the value is null or if the * conversion fails * @return the value in the map as a number, or defaultValue if the * original value is null, the map is null or the number conversion * fails */ public static Double getDouble(Map map, Object key, Double defaultValue) { Double answer = getDouble(map, key); if (answer == null) { answer = defaultValue; } return answer; } /** * Looks up the given key in the given map, converting the result into * a map, using the default value if the the conversion fails. * * @param map the map whose value to look up * @param key the key of the value to look up in that map * @param defaultValue what to return if the value is null or if the * conversion fails * @return the value in the map as a number, or defaultValue if the * original value is null, the map is null or the map conversion * fails */ public static Map getMap(Map> map, K key, Map defaultValue) { Map answer = getMap(map, key); if (answer == null) { answer = defaultValue; } return answer; } // Type safe primitive getters //------------------------------------------------------------------------- /** * Gets a boolean from a Map in a null-safe manner. *

      * If the value is a Boolean its value is returned. * If the value is a String and it equals 'true' ignoring case * then true is returned, otherwise false. * If the value is a Number an integer zero value returns * false and non-zero returns true. * Otherwise, false is returned. * * @param map the map to use * @param key the key to look up * @return the value in the Map as a Boolean, false if null map input */ public static boolean getBooleanValue(final Map map, final Object key) { Boolean booleanObject = getBoolean(map, key); if (booleanObject == null) { return false; } return booleanObject.booleanValue(); } /** * Gets a byte from a Map in a null-safe manner. *

      * The byte is obtained from the results of {@link #getNumber(Map,Object)}. * * @param map the map to use * @param key the key to look up * @return the value in the Map as a byte, 0 if null map input */ public static byte getByteValue(final Map map, final Object key) { Byte byteObject = getByte(map, key); if (byteObject == null) { return 0; } return byteObject.byteValue(); } /** * Gets a short from a Map in a null-safe manner. *

      * The short is obtained from the results of {@link #getNumber(Map,Object)}. * * @param map the map to use * @param key the key to look up * @return the value in the Map as a short, 0 if null map input */ public static short getShortValue(final Map map, final Object key) { Short shortObject = getShort(map, key); if (shortObject == null) { return 0; } return shortObject.shortValue(); } /** * Gets an int from a Map in a null-safe manner. *

      * The int is obtained from the results of {@link #getNumber(Map,Object)}. * * @param map the map to use * @param key the key to look up * @return the value in the Map as an int, 0 if null map input */ public static int getIntValue(final Map map, final Object key) { Integer integerObject = getInteger(map, key); if (integerObject == null) { return 0; } return integerObject.intValue(); } /** * Gets a long from a Map in a null-safe manner. *

      * The long is obtained from the results of {@link #getNumber(Map,Object)}. * * @param map the map to use * @param key the key to look up * @return the value in the Map as a long, 0L if null map input */ public static long getLongValue(final Map map, final Object key) { Long longObject = getLong(map, key); if (longObject == null) { return 0L; } return longObject.longValue(); } /** * Gets a float from a Map in a null-safe manner. *

      * The float is obtained from the results of {@link #getNumber(Map,Object)}. * * @param map the map to use * @param key the key to look up * @return the value in the Map as a float, 0.0F if null map input */ public static float getFloatValue(final Map map, final Object key) { Float floatObject = getFloat(map, key); if (floatObject == null) { return 0f; } return floatObject.floatValue(); } /** * Gets a double from a Map in a null-safe manner. *

      * The double is obtained from the results of {@link #getNumber(Map,Object)}. * * @param map the map to use * @param key the key to look up * @return the value in the Map as a double, 0.0 if null map input */ public static double getDoubleValue(final Map map, final Object key) { Double doubleObject = getDouble(map, key); if (doubleObject == null) { return 0d; } return doubleObject.doubleValue(); } // Type safe primitive getters with default values //------------------------------------------------------------------------- /** * Gets a boolean from a Map in a null-safe manner, * using the default value if the the conversion fails. *

      * If the value is a Boolean its value is returned. * If the value is a String and it equals 'true' ignoring case * then true is returned, otherwise false. * If the value is a Number an integer zero value returns * false and non-zero returns true. * Otherwise, defaultValue is returned. * * @param map the map to use * @param key the key to look up * @param defaultValue return if the value is null or if the * conversion fails * @return the value in the Map as a Boolean, defaultValue if null map input */ public static boolean getBooleanValue(final Map map, final Object key, boolean defaultValue) { Boolean booleanObject = getBoolean(map, key); if (booleanObject == null) { return defaultValue; } return booleanObject.booleanValue(); } /** * Gets a byte from a Map in a null-safe manner, * using the default value if the the conversion fails. *

      * The byte is obtained from the results of {@link #getNumber(Map,Object)}. * * @param map the map to use * @param key the key to look up * @param defaultValue return if the value is null or if the * conversion fails * @return the value in the Map as a byte, defaultValue if null map input */ public static byte getByteValue(final Map map, final Object key, byte defaultValue) { Byte byteObject = getByte(map, key); if (byteObject == null) { return defaultValue; } return byteObject.byteValue(); } /** * Gets a short from a Map in a null-safe manner, * using the default value if the the conversion fails. *

      * The short is obtained from the results of {@link #getNumber(Map,Object)}. * * @param map the map to use * @param key the key to look up * @param defaultValue return if the value is null or if the * conversion fails * @return the value in the Map as a short, defaultValue if null map input */ public static short getShortValue(final Map map, final Object key, short defaultValue) { Short shortObject = getShort(map, key); if (shortObject == null) { return defaultValue; } return shortObject.shortValue(); } /** * Gets an int from a Map in a null-safe manner, * using the default value if the the conversion fails. *

      * The int is obtained from the results of {@link #getNumber(Map,Object)}. * * @param map the map to use * @param key the key to look up * @param defaultValue return if the value is null or if the * conversion fails * @return the value in the Map as an int, defaultValue if null map input */ public static int getIntValue(final Map map, final Object key, int defaultValue) { Integer integerObject = getInteger(map, key); if (integerObject == null) { return defaultValue; } return integerObject.intValue(); } /** * Gets a long from a Map in a null-safe manner, * using the default value if the the conversion fails. *

      * The long is obtained from the results of {@link #getNumber(Map,Object)}. * * @param map the map to use * @param key the key to look up * @param defaultValue return if the value is null or if the * conversion fails * @return the value in the Map as a long, defaultValue if null map input */ public static long getLongValue(final Map map, final Object key, long defaultValue) { Long longObject = getLong(map, key); if (longObject == null) { return defaultValue; } return longObject.longValue(); } /** * Gets a float from a Map in a null-safe manner, * using the default value if the the conversion fails. *

      * The float is obtained from the results of {@link #getNumber(Map,Object)}. * * @param map the map to use * @param key the key to look up * @param defaultValue return if the value is null or if the * conversion fails * @return the value in the Map as a float, defaultValue if null map input */ public static float getFloatValue(final Map map, final Object key, float defaultValue) { Float floatObject = getFloat(map, key); if (floatObject == null) { return defaultValue; } return floatObject.floatValue(); } /** * Gets a double from a Map in a null-safe manner, * using the default value if the the conversion fails. *

      * The double is obtained from the results of {@link #getNumber(Map,Object)}. * * @param map the map to use * @param key the key to look up * @param defaultValue return if the value is null or if the * conversion fails * @return the value in the Map as a double, defaultValue if null map input */ public static double getDoubleValue(final Map map, final Object key, double defaultValue) { Double doubleObject = getDouble(map, key); if (doubleObject == null) { return defaultValue; } return doubleObject.doubleValue(); } // Conversion methods //------------------------------------------------------------------------- /** * Gets a new Properties object initialised with the values from a Map. * A null input will return an empty properties object. * * @param map the map to convert to a Properties object, may not be null * @return the properties object */ public static Properties toProperties(final Map map) { Properties answer = new Properties(); if (map != null) { for (Iterator iter = map.entrySet().iterator(); iter.hasNext();) { Map.Entry entry = (Map.Entry) iter.next(); Object key = entry.getKey(); Object value = entry.getValue(); answer.put(key, value); } } return answer; } /** * Creates a new HashMap using data copied from a ResourceBundle. * * @param resourceBundle the resource bundle to convert, may not be null * @return the hashmap containing the data * @throws NullPointerException if the bundle is null */ public static Map toMap(final ResourceBundle resourceBundle) { Enumeration enumeration = resourceBundle.getKeys(); Map map = new HashMap(); while (enumeration.hasMoreElements()) { String key = enumeration.nextElement(); Object value = resourceBundle.getObject(key); map.put(key, value); } return map; } // Printing methods //------------------------------------------------------------------------- /** * Prints the given map with nice line breaks. *

      * This method prints a nicely formatted String describing the Map. * Each map entry will be printed with key and value. * When the value is a Map, recursive behaviour occurs. *

      * This method is NOT thread-safe in any special way. You must manually * synchronize on either this class or the stream as required. * * @param out the stream to print to, must not be null * @param label The label to be used, may be null. * If null, the label is not output. * It typically represents the name of the property in a bean or similar. * @param map The map to print, may be null. * If null, the text 'null' is output. * @throws NullPointerException if the stream is null */ public static void verbosePrint(final PrintStream out, final Object label, final Map map) { verbosePrintInternal(out, label, map, new ArrayStack(), false); } /** * Prints the given map with nice line breaks. *

      * This method prints a nicely formatted String describing the Map. * Each map entry will be printed with key, value and value classname. * When the value is a Map, recursive behaviour occurs. *

      * This method is NOT thread-safe in any special way. You must manually * synchronize on either this class or the stream as required. * * @param out the stream to print to, must not be null * @param label The label to be used, may be null. * If null, the label is not output. * It typically represents the name of the property in a bean or similar. * @param map The map to print, may be null. * If null, the text 'null' is output. * @throws NullPointerException if the stream is null */ public static void debugPrint(final PrintStream out, final Object label, final Map map) { verbosePrintInternal(out, label, map, new ArrayStack(), true); } // Implementation methods //------------------------------------------------------------------------- /** * Logs the given exception to System.out. *

      * This method exists as Jakarta Collections does not depend on logging. * * @param ex the exception to log */ protected static void logInfo(final Exception ex) { System.out.println("INFO: Exception: " + ex); } /** * Implementation providing functionality for {@link #debugPrint} and for * {@link #verbosePrint}. This prints the given map with nice line breaks. * If the debug flag is true, it additionally prints the type of the object * value. If the contents of a map include the map itself, then the text * (this Map) is printed out. If the contents include a * parent container of the map, the the text (ancestor[i] Map) is * printed, where i actually indicates the number of levels which must be * traversed in the sequential list of ancestors (e.g. father, grandfather, * great-grandfather, etc). * * @param out the stream to print to * @param label the label to be used, may be null. * If null, the label is not output. * It typically represents the name of the property in a bean or similar. * @param map the map to print, may be null. * If null, the text 'null' is output * @param lineage a stack consisting of any maps in which the previous * argument is contained. This is checked to avoid infinite recursion when * printing the output * @param debug flag indicating whether type names should be output. * @throws NullPointerException if the stream is null */ private static void verbosePrintInternal(final PrintStream out, final Object label, final Map map, final ArrayStack lineage, final boolean debug) { printIndent(out, lineage.size()); if (map == null) { if (label != null) { out.print(label); out.print(" = "); } out.println("null"); return; } if (label != null) { out.print(label); out.println(" = "); } printIndent(out, lineage.size()); out.println("{"); lineage.push(map); for (Iterator it = map.entrySet().iterator(); it.hasNext();) { Map.Entry entry = (Map.Entry) it.next(); Object childKey = entry.getKey(); Object childValue = entry.getValue(); if (childValue instanceof Map && !lineage.contains(childValue)) { verbosePrintInternal(out, (childKey == null ? "null" : childKey), (Map) childValue, lineage, debug); } else { printIndent(out, lineage.size()); out.print(childKey); out.print(" = "); final int lineageIndex = lineage.indexOf(childValue); if (lineageIndex == -1) { out.print(childValue); } else if (lineage.size() - 1 == lineageIndex) { out.print("(this Map)"); } else { out.print("(ancestor[" + (lineage.size() - 1 - lineageIndex - 1) + "] Map)"); } if (debug && childValue != null) { out.print(' '); out.println(childValue.getClass().getName()); } else { out.println(); } } } lineage.pop(); printIndent(out, lineage.size()); out.println(debug ? "} " + map.getClass().getName() : "}"); } /** * Writes indentation to the given stream. * * @param out the stream to indent */ private static void printIndent(final PrintStream out, final int indent) { for (int i = 0; i < indent; i++) { out.print(INDENT_STRING); } } // Misc //----------------------------------------------------------------------- /** * Inverts the supplied map returning a new HashMap such that the keys of * the input are swapped with the values. *

      * This operation assumes that the inverse mapping is well defined. * If the input map had multiple entries with the same value mapped to * different keys, the returned map will map one of those keys to the * value, but the exact key which will be mapped is undefined. * * @param map the map to invert, may not be null * @return a new HashMap containing the inverted data * @throws NullPointerException if the map is null */ public static Map invertMap(Map map) { Map out = new HashMap(map.size()); for (Iterator> it = map.entrySet().iterator(); it.hasNext();) { Map.Entry entry = it.next(); out.put(entry.getValue(), entry.getKey()); } return out; } /** * Nice method for adding data to a map in such a way * as to not get NPE's. The point being that if the * value is null, map.put() will throw an exception. * That blows in the case of this class cause you may want to * essentially treat put("Not Null", null ) == put("Not Null", "") * We will still throw a NPE if the key is null cause that should * never happen. *

      * Note: this is not a type-safe operation in Java 1.5. * * @param map the map to add to, may not be null * @param key the key * @param value the value * @throws NullPointerException if the map is null * */ public static void safeAddToMap(Map map, Object key, Object value) throws NullPointerException { if (value == null) { map.put(key, ""); } else { map.put(key, value); } } // Map decorators //----------------------------------------------------------------------- /** * Returns a synchronized map backed by the given map. *

      * You must manually synchronize on the returned buffer's iterator to * avoid non-deterministic behavior: *

      *

           * Map m = MapUtils.synchronizedMap(myMap);
           * Set s = m.keySet();  // outside synchronized block
           * synchronized (m) {  // synchronized on MAP!
           *     Iterator i = s.iterator();
           *     while (i.hasNext()) {
           *         process (i.next());
           *     }
           * }
           * 
      *

      * This method uses the implementation in {@link java.util.Collections Collections}. * * @param map the map to synchronize, must not be null * @return a synchronized map backed by the given map * @throws IllegalArgumentException if the map is null */ public static Map synchronizedMap(Map map) { return Collections.synchronizedMap(map); } /** * Returns an unmodifiable map backed by the given map. *

      * This method uses the implementation in the decorators subpackage. * * @param map the map to make unmodifiable, must not be null * @return an unmodifiable map backed by the given map * @throws IllegalArgumentException if the map is null */ public static Map unmodifiableMap(Map map) { return UnmodifiableMap.decorate(map); } /** * Returns a predicated (validating) map backed by the given map. *

      * Only objects that pass the tests in the given predicates can be added to the map. * Trying to add an invalid object results in an IllegalArgumentException. * Keys must pass the key predicate, values must pass the value predicate. * It is important not to use the original map after invoking this method, * as it is a backdoor for adding invalid objects. * * @param map the map to predicate, must not be null * @param keyPred the predicate for keys, null means no check * @param valuePred the predicate for values, null means no check * @return a predicated map backed by the given map * @throws IllegalArgumentException if the Map is null */ public static Map predicatedMap(Map map, Predicate keyPred, Predicate valuePred) { return PredicatedMap.decorate(map, keyPred, valuePred); } /** * Returns a typed map backed by the given map. *

      * Only keys and values of the specified types can be added to the map. * * @param map the map to limit to a specific type, must not be null * @param keyType the type of keys which may be added to the map, must not be null * @param valueType the type of values which may be added to the map, must not be null * @return a typed map backed by the specified map * @throws IllegalArgumentException if the Map or Class is null * @deprecated this is no longer needed with Java generics. */ public static Map typedMap(Map map, Class keyType, Class valueType) { return TypedMap.decorate(map, keyType, valueType); } /** * Returns a transformed map backed by the given map. *

      * Each object is passed through the transformers as it is added to the * Map. It is important not to use the original map after invoking this * method, as it is a backdoor for adding untransformed objects. * * @param map the map to transform, must not be null * @param keyTransformer the transformer for the map keys, null means no transformation * @param valueTransformer the transformer for the map values, null means no transformation * @return a transformed map backed by the given map * @throws IllegalArgumentException if the Map is null */ public static Map transformedMap(Map map, Transformer keyTransformer, Transformer valueTransformer) { return TransformedMap.decorate(map, keyTransformer, valueTransformer); } /** * Returns a fixed-sized map backed by the given map. * Elements may not be added or removed from the returned map, but * existing elements can be changed (for instance, via the * {@link Map#put(Object,Object)} method). * * @param map the map whose size to fix, must not be null * @return a fixed-size map backed by that map * @throws IllegalArgumentException if the Map is null */ public static Map fixedSizeMap(Map map) { return FixedSizeMap.decorate(map); } /** * Returns a "lazy" map whose values will be created on demand. *

      * When the key passed to the returned map's {@link Map#get(Object)} * method is not present in the map, then the factory will be used * to create a new object and that object will become the value * associated with that key. *

      * For instance: *

           * Factory factory = new Factory() {
           *     public Object create() {
           *         return new Date();
           *     }
           * }
           * Map lazyMap = MapUtils.lazyMap(new HashMap(), factory);
           * Object obj = lazyMap.get("test");
           * 
      *

      * After the above code is executed, obj will contain * a new Date instance. Furthermore, that Date * instance is the value for the "test" key in the map. * * @param map the map to make lazy, must not be null * @param factory the factory for creating new objects, must not be null * @return a lazy map backed by the given map * @throws IllegalArgumentException if the Map or Factory is null */ public static Map lazyMap(Map map, Factory factory) { return LazyMap.decorate(map, factory); } /** * Returns a map that maintains the order of keys that are added * backed by the given map. *

      * If a key is added twice, the order is determined by the first add. * The order is observed through the keySet, values and entrySet. * * @param map the map to order, must not be null * @return an ordered map backed by the given map * @throws IllegalArgumentException if the Map is null */ public static Map orderedMap(Map map) { return ListOrderedMap.decorate(map); } // SortedMap decorators //----------------------------------------------------------------------- /** * Returns a synchronized sorted map backed by the given sorted map. *

      * You must manually synchronize on the returned buffer's iterator to * avoid non-deterministic behavior: *

      *

           * Map m = MapUtils.synchronizedSortedMap(myMap);
           * Set s = m.keySet();  // outside synchronized block
           * synchronized (m) {  // synchronized on MAP!
           *     Iterator i = s.iterator();
           *     while (i.hasNext()) {
           *         process (i.next());
           *     }
           * }
           * 
      *

      * This method uses the implementation in {@link java.util.Collections Collections}. * * @param map the map to synchronize, must not be null * @return a synchronized map backed by the given map * @throws IllegalArgumentException if the map is null */ public static Map synchronizedSortedMap(SortedMap map) { return Collections.synchronizedSortedMap(map); } /** * Returns an unmodifiable sorted map backed by the given sorted map. *

      * This method uses the implementation in the decorators subpackage. * * @param map the sorted map to make unmodifiable, must not be null * @return an unmodifiable map backed by the given map * @throws IllegalArgumentException if the map is null */ public static Map unmodifiableSortedMap(SortedMap map) { return UnmodifiableSortedMap.decorate(map); } /** * Returns a predicated (validating) sorted map backed by the given map. *

      * Only objects that pass the tests in the given predicates can be added to the map. * Trying to add an invalid object results in an IllegalArgumentException. * Keys must pass the key predicate, values must pass the value predicate. * It is important not to use the original map after invoking this method, * as it is a backdoor for adding invalid objects. * * @param map the map to predicate, must not be null * @param keyPred the predicate for keys, null means no check * @param valuePred the predicate for values, null means no check * @return a predicated map backed by the given map * @throws IllegalArgumentException if the SortedMap is null */ public static SortedMap predicatedSortedMap(SortedMap map, Predicate keyPred, Predicate valuePred) { return PredicatedSortedMap.decorate(map, keyPred, valuePred); } /** * Returns a typed sorted map backed by the given map. *

      * Only keys and values of the specified types can be added to the map. * * @param map the map to limit to a specific type, must not be null * @param keyType the type of keys which may be added to the map, must not be null * @param valueType the type of values which may be added to the map, must not be null * @return a typed map backed by the specified map * @deprecated no longer needed with Java generics. */ public static SortedMap typedSortedMap(SortedMap map, Class keyType, Class valueType) { return TypedSortedMap.decorate(map, keyType, valueType); } /** * Returns a transformed sorted map backed by the given map. *

      * Each object is passed through the transformers as it is added to the * Map. It is important not to use the original map after invoking this * method, as it is a backdoor for adding untransformed objects. * * @param map the map to transform, must not be null * @param keyTransformer the transformer for the map keys, null means no transformation * @param valueTransformer the transformer for the map values, null means no transformation * @return a transformed map backed by the given map * @throws IllegalArgumentException if the SortedMap is null */ public static SortedMap transformedSortedMap(SortedMap map, Transformer keyTransformer, Transformer valueTransformer) { return TransformedSortedMap.decorate(map, keyTransformer, valueTransformer); } /** * Returns a fixed-sized sorted map backed by the given sorted map. * Elements may not be added or removed from the returned map, but * existing elements can be changed (for instance, via the * {@link Map#put(Object,Object)} method). * * @param map the map whose size to fix, must not be null * @return a fixed-size map backed by that map * @throws IllegalArgumentException if the SortedMap is null */ public static SortedMap fixedSizeSortedMap(SortedMap map) { return FixedSizeSortedMap.decorate(map); } /** * Returns a "lazy" sorted map whose values will be created on demand. *

      * When the key passed to the returned map's {@link Map#get(Object)} * method is not present in the map, then the factory will be used * to create a new object and that object will become the value * associated with that key. *

      * For instance: *

      *

           * Factory factory = new Factory() {
           *     public Object create() {
           *         return new Date();
           *     }
           * }
           * SortedMap lazy = MapUtils.lazySortedMap(new TreeMap(), factory);
           * Object obj = lazy.get("test");
           * 
      *

      * After the above code is executed, obj will contain * a new Date instance. Furthermore, that Date * instance is the value for the "test" key. * * @param map the map to make lazy, must not be null * @param factory the factory for creating new objects, must not be null * @return a lazy map backed by the given map * @throws IllegalArgumentException if the SortedMap or Factory is null */ public static SortedMap lazySortedMap(SortedMap map, Factory factory) { return LazySortedMap.decorate(map, factory); } } collections-generic-4.01/src/java/org/apache/commons/collections15/set/0000755000175000017500000000000011664401370026250 5ustar giovannigiovannicollections-generic-4.01/src/java/org/apache/commons/collections15/set/PredicatedSortedSet.java0000644000175000017500000001005710464140760033017 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.set; import org.apache.commons.collections15.Predicate; import java.util.Comparator; import java.util.SortedSet; /** * Decorates another SortedSet to validate that all additions * match a specified predicate. *

      * This set exists to provide validation for the decorated set. * It is normally created to decorate an empty set. * If an object cannot be added to the set, an IllegalArgumentException is thrown. *

      * One usage would be to ensure that no null entries are added to the set. *

      SortedSet set = PredicatedSortedSet.decorate(new TreeSet(), NotNullPredicate.INSTANCE);
      *

      * This class is Serializable from Commons Collections 3.1. * * @author Stephen Colebourne * @author Matt Hall, John Watkinson, Paul Jack * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:39 $ * @since Commons Collections 3.0 */ public class PredicatedSortedSet extends PredicatedSet implements SortedSet { /** * Serialization version */ private static final long serialVersionUID = -9110948148132275052L; /** * Factory method to create a predicated (validating) sorted set. *

      * If there are any elements already in the set being decorated, they * are validated. * * @param set the set to decorate, must not be null * @param predicate the predicate to use for validation, must not be null * @throws IllegalArgumentException if set or predicate is null * @throws IllegalArgumentException if the set contains invalid elements */ public static SortedSet decorate(SortedSet set, Predicate predicate) { return new PredicatedSortedSet(set, predicate); } //----------------------------------------------------------------------- /** * Constructor that wraps (not copies). *

      * If there are any elements already in the set being decorated, they * are validated. * * @param set the set to decorate, must not be null * @param predicate the predicate to use for validation, must not be null * @throws IllegalArgumentException if set or predicate is null * @throws IllegalArgumentException if the set contains invalid elements */ protected PredicatedSortedSet(SortedSet set, Predicate predicate) { super(set, predicate); } /** * Gets the sorted set being decorated. * * @return the decorated sorted set */ private SortedSet getSortedSet() { return (SortedSet) getCollection(); } //----------------------------------------------------------------------- public SortedSet subSet(E fromElement, E toElement) { SortedSet sub = getSortedSet().subSet(fromElement, toElement); return new PredicatedSortedSet(sub, predicate); } public SortedSet headSet(E toElement) { SortedSet sub = getSortedSet().headSet(toElement); return new PredicatedSortedSet(sub, predicate); } public SortedSet tailSet(E fromElement) { SortedSet sub = getSortedSet().tailSet(fromElement); return new PredicatedSortedSet(sub, predicate); } public E first() { return getSortedSet().first(); } public E last() { return getSortedSet().last(); } public Comparator comparator() { return getSortedSet().comparator(); } } collections-generic-4.01/src/java/org/apache/commons/collections15/set/PredicatedSet.java0000644000175000017500000000623710464140756031650 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.set; import org.apache.commons.collections15.Predicate; import org.apache.commons.collections15.collection.PredicatedCollection; import java.util.Set; /** * Decorates another Set to validate that all additions * match a specified predicate. *

      * This set exists to provide validation for the decorated set. * It is normally created to decorate an empty set. * If an object cannot be added to the set, an IllegalArgumentException is thrown. *

      * One usage would be to ensure that no null entries are added to the set. *

      Set set = PredicatedSet.decorate(new HashSet(), NotNullPredicate.INSTANCE);
      *

      * This class is Serializable from Commons Collections 3.1. * * @author Stephen Colebourne * @author Matt Hall, John Watkinson, Paul Jack * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:39 $ * @since Commons Collections 3.0 */ public class PredicatedSet extends PredicatedCollection implements Set { /** * Serialization version */ private static final long serialVersionUID = -684521469108685117L; /** * Factory method to create a predicated (validating) set. *

      * If there are any elements already in the set being decorated, they * are validated. * * @param set the set to decorate, must not be null * @param predicate the predicate to use for validation, must not be null * @throws IllegalArgumentException if set or predicate is null * @throws IllegalArgumentException if the set contains invalid elements */ public static Set decorate(Set set, Predicate predicate) { return new PredicatedSet(set, predicate); } //----------------------------------------------------------------------- /** * Constructor that wraps (not copies). *

      * If there are any elements already in the set being decorated, they * are validated. * * @param set the set to decorate, must not be null * @param predicate the predicate to use for validation, must not be null * @throws IllegalArgumentException if set or predicate is null * @throws IllegalArgumentException if the set contains invalid elements */ protected PredicatedSet(Set set, Predicate predicate) { super(set, predicate); } /** * Gets the set being decorated. * * @return the decorated set */ protected Set getSet() { return (Set) getCollection(); } } collections-generic-4.01/src/java/org/apache/commons/collections15/set/SynchronizedSet.java0000644000175000017500000000474010464140765032260 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.set; import org.apache.commons.collections15.collection.SynchronizedCollection; import java.util.Set; /** * Decorates another Set to synchronize its behaviour for a * multi-threaded environment. *

      * Methods are synchronized, then forwarded to the decorated set. *

      * This class is Serializable from Commons Collections 3.1. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:39 $ * @since Commons Collections 3.0 */ public class SynchronizedSet extends SynchronizedCollection implements Set { /** * Serialization version */ private static final long serialVersionUID = -8304417378626543635L; /** * Factory method to create a synchronized set. * * @param set the set to decorate, must not be null * @throws IllegalArgumentException if set is null */ public static Set decorate(Set set) { return new SynchronizedSet(set); } //----------------------------------------------------------------------- /** * Constructor that wraps (not copies). * * @param set the set to decorate, must not be null * @throws IllegalArgumentException if set is null */ protected SynchronizedSet(Set set) { super(set); } /** * Constructor that wraps (not copies). * * @param set the set to decorate, must not be null * @param lock the lock object to use, must not be null * @throws IllegalArgumentException if set is null */ protected SynchronizedSet(Set set, Object lock) { super(set, lock); } /** * Gets the decorated set. * * @return the decorated set */ protected Set getSet() { return (Set) collection; } } collections-generic-4.01/src/java/org/apache/commons/collections15/set/TransformedSet.java0000644000175000017500000000546710464140754032072 0ustar giovannigiovanni// TODO: Not yet converted - deprecated (by me). /* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.set; import org.apache.commons.collections15.Transformer; import org.apache.commons.collections15.collection.TransformedCollection; import java.util.Set; /** * Decorates another Set to transform objects that are added. *

      * The add methods are affected by this class. * Thus objects must be removed or searched for using their transformed form. * For example, if the transformation converts Strings to Integers, you must * use the Integer form to remove objects. *

      * This class is Serializable from Commons Collections 3.1. *

      * Note: This class cannot support generics without breaking the Collection contract. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:39 $ * @since Commons Collections 3.0 */ public class TransformedSet extends TransformedCollection implements Set { /** * Serialization version */ private static final long serialVersionUID = 306127383500410386L; /** * Factory method to create a transforming set. *

      * If there are any elements already in the set being decorated, they * are NOT transformed. * * @param set the set to decorate, must not be null * @param transformer the transformer to use for conversion, must not be null * @throws IllegalArgumentException if set or transformer is null */ public static Set decorate(Set set, Transformer transformer) { return new TransformedSet(set, transformer); } //----------------------------------------------------------------------- /** * Constructor that wraps (not copies). *

      * If there are any elements already in the set being decorated, they * are NOT transformed. * * @param set the set to decorate, must not be null * @param transformer the transformer to use for conversion, must not be null * @throws IllegalArgumentException if set or transformer is null */ protected TransformedSet(Set set, Transformer transformer) { super(set, transformer); } } collections-generic-4.01/src/java/org/apache/commons/collections15/set/MapBackedSet.java0000644000175000017500000001113010464140757031400 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.set; import java.io.Serializable; import java.util.Collection; import java.util.Iterator; import java.util.Map; import java.util.Set; /** * Decorates a Map to obtain Set behaviour. *

      * This class is used to create a Set with the same properties as * the key set of any map. Thus, a ReferenceSet can be created by wrapping a * ReferenceMap in an instance of this class. *

      * Most map implementation can be used to create a set by passing in dummy values. * Exceptions include BidiMap implementations, as they require unique values. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:39 $ * @since Commons Collections 3.1 */ public final class MapBackedSet implements Set, Serializable { /** * Serialization version */ private static final long serialVersionUID = 6723912213766056587L; /** * The map being used as the backing store */ protected final Map map; /** * The dummyValue to use */ protected final V dummyValue; /** * Factory method to create a set from a map. * * @param map the map to decorate, must not be null * @throws IllegalArgumentException if set is null */ public static Set decorate(Map map) { return decorate(map, null); } /** * Factory method to create a set from a map. * * @param map the map to decorate, must not be null * @param dummyValue the dummy value to use * @throws IllegalArgumentException if map is null */ public static Set decorate(Map map, V dummyValue) { if (map == null) { throw new IllegalArgumentException("The map must not be null"); } return new MapBackedSet(map, dummyValue); } //----------------------------------------------------------------------- /** * Constructor that wraps (not copies). * * @param map the map to decorate, must not be null * @param dummyValue the dummy value to use * @throws IllegalArgumentException if map is null */ private MapBackedSet(Map map, V dummyValue) { super(); this.map = map; this.dummyValue = dummyValue; } //----------------------------------------------------------------------- public int size() { return map.size(); } public boolean isEmpty() { return map.isEmpty(); } public Iterator iterator() { return map.keySet().iterator(); } public boolean contains(Object obj) { return map.containsKey(obj); } public boolean containsAll(Collection coll) { return map.keySet().containsAll(coll); } public boolean add(K obj) { int size = map.size(); map.put(obj, dummyValue); return (map.size() != size); } public boolean addAll(Collection coll) { int size = map.size(); for (Iterator it = coll.iterator(); it.hasNext();) { K obj = it.next(); map.put(obj, dummyValue); } return (map.size() != size); } public boolean remove(Object obj) { int size = map.size(); map.remove(obj); return (map.size() != size); } public boolean removeAll(Collection coll) { return map.keySet().removeAll(coll); } public boolean retainAll(Collection coll) { return map.keySet().retainAll(coll); } public void clear() { map.clear(); } public Object[] toArray() { return map.keySet().toArray(); } public T[] toArray(T[] array) { return map.keySet().toArray(array); } public boolean equals(Object obj) { return map.keySet().equals(obj); } public int hashCode() { return map.keySet().hashCode(); } } collections-generic-4.01/src/java/org/apache/commons/collections15/set/TypedSortedSet.java0000644000175000017500000000376510464140762032052 0ustar giovannigiovanni// TODO: Not yet converted. /* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.set; import org.apache.commons.collections15.functors.InstanceofPredicate; import java.util.SortedSet; /** * Decorates another SortedSet to validate that elements * added are of a specific type. *

      * The validation of additions is performed via an instanceof test against * a specified Class. If an object cannot be added to the * collection, an IllegalArgumentException is thrown. * * @author Stephen Colebourne * @author Matt Hall, John Watkinson, Matthew Hawthorne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:39 $ * @since Commons Collections 3.0 */ public class TypedSortedSet { /** * Factory method to create a typed sorted set. *

      * If there are any elements already in the set being decorated, they * are validated. * * @param set the set to decorate, must not be null * @param type the type to allow into the collection, must not be null * @throws IllegalArgumentException if set or type is null * @throws IllegalArgumentException if the set contains invalid elements */ public static SortedSet decorate(SortedSet set, Class type) { return new PredicatedSortedSet(set, InstanceofPredicate.getInstance(type)); } /** * Restrictive constructor. */ protected TypedSortedSet() { } } collections-generic-4.01/src/java/org/apache/commons/collections15/set/UnmodifiableSet.java0000644000175000017500000000556710464140764032206 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.set; import org.apache.commons.collections15.Unmodifiable; import org.apache.commons.collections15.iterators.UnmodifiableIterator; import java.util.Collection; import java.util.Iterator; import java.util.Set; /** * Decorates another Set to ensure it can't be altered. *

      * This class is Serializable from Commons Collections 3.1. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:39 $ * @since Commons Collections 3.0 */ public final class UnmodifiableSet extends AbstractSerializableSetDecorator implements Unmodifiable { /** * Serialization version */ private static final long serialVersionUID = 6499119872185240161L; /** * Factory method to create an unmodifiable set. * * @param set the set to decorate, must not be null * @throws IllegalArgumentException if set is null */ public static Set decorate(Set set) { if (set instanceof Unmodifiable) { return set; } return new UnmodifiableSet(set); } //----------------------------------------------------------------------- /** * Constructor that wraps (not copies). * * @param set the set to decorate, must not be null * @throws IllegalArgumentException if set is null */ private UnmodifiableSet(Set set) { super(set); } //----------------------------------------------------------------------- public Iterator iterator() { return UnmodifiableIterator.decorate(getCollection().iterator()); } public boolean add(E object) { throw new UnsupportedOperationException(); } public boolean addAll(Collection coll) { throw new UnsupportedOperationException(); } public void clear() { throw new UnsupportedOperationException(); } public boolean remove(Object object) { throw new UnsupportedOperationException(); } public boolean removeAll(Collection coll) { throw new UnsupportedOperationException(); } public boolean retainAll(Collection coll) { throw new UnsupportedOperationException(); } } collections-generic-4.01/src/java/org/apache/commons/collections15/set/UnmodifiableSortedSet.java0000644000175000017500000001055010464140762033351 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.set; import org.apache.commons.collections15.Unmodifiable; import org.apache.commons.collections15.iterators.UnmodifiableIterator; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.Collection; import java.util.Iterator; import java.util.SortedSet; /** * Decorates another SortedSet to ensure it can't be altered. *

      * This class is Serializable from Commons Collections 3.1. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:39 $ * @since Commons Collections 3.0 */ public final class UnmodifiableSortedSet extends AbstractSortedSetDecorator implements Unmodifiable, Serializable { /** * Serialization version */ private static final long serialVersionUID = -725356885467962424L; /** * Factory method to create an unmodifiable set. * * @param set the set to decorate, must not be null * @throws IllegalArgumentException if set is null */ public static SortedSet decorate(SortedSet set) { if (set instanceof Unmodifiable) { return set; } return new UnmodifiableSortedSet(set); } //----------------------------------------------------------------------- /** * Write the collection out using a custom routine. * * @param out the output stream * @throws IOException */ private void writeObject(ObjectOutputStream out) throws IOException { out.defaultWriteObject(); out.writeObject(collection); } /** * Read the collection in using a custom routine. * * @param in the input stream * @throws IOException * @throws ClassNotFoundException */ private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); collection = (Collection) in.readObject(); } //----------------------------------------------------------------------- /** * Constructor that wraps (not copies). * * @param set the set to decorate, must not be null * @throws IllegalArgumentException if set is null */ private UnmodifiableSortedSet(SortedSet set) { super(set); } //----------------------------------------------------------------------- public Iterator iterator() { return UnmodifiableIterator.decorate(getCollection().iterator()); } public boolean add(E object) { throw new UnsupportedOperationException(); } public boolean addAll(Collection coll) { throw new UnsupportedOperationException(); } public void clear() { throw new UnsupportedOperationException(); } public boolean remove(Object object) { throw new UnsupportedOperationException(); } public boolean removeAll(Collection coll) { throw new UnsupportedOperationException(); } public boolean retainAll(Collection coll) { throw new UnsupportedOperationException(); } //----------------------------------------------------------------------- public SortedSet subSet(E fromElement, E toElement) { SortedSet sub = getSortedSet().subSet(fromElement, toElement); return new UnmodifiableSortedSet(sub); } public SortedSet headSet(E toElement) { SortedSet sub = getSortedSet().headSet(toElement); return new UnmodifiableSortedSet(sub); } public SortedSet tailSet(E fromElement) { SortedSet sub = getSortedSet().tailSet(fromElement); return new UnmodifiableSortedSet(sub); } } ././@LongLink0000000000000000000000000000015500000000000011566 Lustar rootrootcollections-generic-4.01/src/java/org/apache/commons/collections15/set/AbstractSerializableSetDecorator.javacollections-generic-4.01/src/java/org/apache/commons/collections15/set/AbstractSerializableSetDecora0000644000175000017500000000410010464140755034056 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.set; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.Collection; import java.util.Set; /** * Serializable subclass of AbstractSetDecorator. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @since Commons Collections 3.1 */ public abstract class AbstractSerializableSetDecorator extends AbstractSetDecorator implements Serializable { /** * Serialization version */ private static final long serialVersionUID = 1229469966212206107L; /** * Constructor. */ protected AbstractSerializableSetDecorator(Set set) { super(set); } //----------------------------------------------------------------------- /** * Write the set out using a custom routine. * * @param out the output stream * @throws IOException */ private void writeObject(ObjectOutputStream out) throws IOException { out.defaultWriteObject(); out.writeObject(collection); } /** * Read the set in using a custom routine. * * @param in the input stream * @throws IOException * @throws ClassNotFoundException */ private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); collection = (Collection) in.readObject(); } } collections-generic-4.01/src/java/org/apache/commons/collections15/set/TypedSet.java0000644000175000017500000000370410464140760030660 0ustar giovannigiovanni// TODO: Not yet converted. /* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.set; import org.apache.commons.collections15.functors.InstanceofPredicate; import java.util.Set; /** * Decorates another Set to validate that elements * added are of a specific type. *

      * The validation of additions is performed via an instanceof test against * a specified Class. If an object cannot be added to the * collection, an IllegalArgumentException is thrown. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @author Matthew Hawthorne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:39 $ * @since Commons Collections 3.0 */ public class TypedSet { /** * Factory method to create a typed set. *

      * If there are any elements already in the set being decorated, they * are validated. * * @param set the set to decorate, must not be null * @param type the type to allow into the collection, must not be null * @throws IllegalArgumentException if set or type is null * @throws IllegalArgumentException if the set contains invalid elements */ public static Set decorate(Set set, Class type) { return new PredicatedSet(set, InstanceofPredicate.getInstance(type)); } /** * Restrictive constructor. */ protected TypedSet() { } } collections-generic-4.01/src/java/org/apache/commons/collections15/set/AbstractSetDecorator.java0000644000175000017500000000345210464140760033201 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.set; import org.apache.commons.collections15.collection.AbstractCollectionDecorator; import java.util.Set; /** * Decorates another Set to provide additional behaviour. *

      * Methods are forwarded directly to the decorated set. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:39 $ * @since Commons Collections 3.0 */ public abstract class AbstractSetDecorator extends AbstractCollectionDecorator implements Set { /** * Constructor only used in deserialization, do not use otherwise. * * @since Commons Collections 3.1 */ protected AbstractSetDecorator() { super(); } /** * Constructor that wraps (not copies). * * @param set the set to decorate, must not be null * @throws IllegalArgumentException if set is null */ protected AbstractSetDecorator(Set set) { super(set); } /** * Gets the set being decorated. * * @return the decorated set */ protected Set getSet() { return (Set) getCollection(); } } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootcollections-generic-4.01/src/java/org/apache/commons/collections15/set/AbstractSortedSetDecorator.javacollections-generic-4.01/src/java/org/apache/commons/collections15/set/AbstractSortedSetDecorator.ja0000644000175000017500000000472110464140761034034 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.set; import java.util.Comparator; import java.util.Set; import java.util.SortedSet; /** * Decorates another SortedSet to provide additional behaviour. *

      * Methods are forwarded directly to the decorated set. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:39 $ * @since Commons Collections 3.0 */ public abstract class AbstractSortedSetDecorator extends AbstractSetDecorator implements SortedSet { /** * Constructor only used in deserialization, do not use otherwise. * * @since Commons Collections 3.1 */ protected AbstractSortedSetDecorator() { super(); } /** * Constructor that wraps (not copies). * * @param set the set to decorate, must not be null * @throws IllegalArgumentException if set is null */ protected AbstractSortedSetDecorator(Set set) { super(set); } /** * Gets the sorted set being decorated. * * @return the decorated set */ protected SortedSet getSortedSet() { return (SortedSet) getCollection(); } //----------------------------------------------------------------------- public SortedSet subSet(E fromElement, E toElement) { return getSortedSet().subSet(fromElement, toElement); } public SortedSet headSet(E toElement) { return getSortedSet().headSet(toElement); } public SortedSet tailSet(E fromElement) { return getSortedSet().tailSet(fromElement); } public E first() { return getSortedSet().first(); } public E last() { return getSortedSet().last(); } public Comparator comparator() { return getSortedSet().comparator(); } } collections-generic-4.01/src/java/org/apache/commons/collections15/set/CompositeSet.java0000644000175000017500000001632410464140764031543 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.set; import org.apache.commons.collections15.CollectionUtils; import org.apache.commons.collections15.collection.CompositeCollection; import java.util.Collection; import java.util.Iterator; import java.util.Set; /** * Decorates a set of other sets to provide a single unified view. *

      * Changes made to this set will actually be made on the decorated set. * Add and remove operations require the use of a pluggable strategy. If no * strategy is provided then add and remove are unsupported. * * @author Matt Hall, John Watkinson, Brian McCallister * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:39 $ * @since Commons Collections 3.0 */ public class CompositeSet extends CompositeCollection implements Set { /** * Create an empty CompositeSet */ public CompositeSet() { super(); } /** * Create a CompositeSet with just set composited * * @param set The initial set in the composite */ public CompositeSet(Set set) { super(set); } /** * Create a composite set with sets as the initial set of composited Sets */ public CompositeSet(Set... sets) { super(sets); } /** * Add a Set to this composite * * @param c Must implement Set * @throws IllegalArgumentException if c does not implement java.util.Set * or if a SetMutator is set, but fails to resolve a collision * @throws UnsupportedOperationException if there is no SetMutator set, or * a CollectionMutator is set instead of a SetMutator * @see org.apache.commons.collections15.collection.CompositeCollection.CollectionMutator * @see SetMutator */ public synchronized void addComposited(Collection c) { if (!(c instanceof Set)) { throw new IllegalArgumentException("Collections added must implement java.util.Set"); } for (Iterator i = this.getCollections().iterator(); i.hasNext();) { Set set = (Set) i.next(); Collection intersects = CollectionUtils.intersection(set, c); if (intersects.size() > 0) { if (this.mutator == null) { throw new UnsupportedOperationException("Collision adding composited collection with no SetMutator set"); } else if (!(this.mutator instanceof SetMutator)) { throw new UnsupportedOperationException("Collision adding composited collection to a CompositeSet with a CollectionMutator instead of a SetMutator"); } ((SetMutator) this.mutator).resolveCollision(this, set, (Set) c, intersects); if (CollectionUtils.intersection(set, c).size() > 0) { throw new IllegalArgumentException("Attempt to add illegal entry unresolved by SetMutator.resolveCollision()"); } } } super.addComposited((Collection[]) new Collection[]{c}); } /** * Add two sets to this composite * * @deprecated Superceded by the variable argument implementation of addComposited() * @throws IllegalArgumentException if c or d does not implement java.util.Set */ public synchronized void addComposited(Collection c, Collection d) { if (!(c instanceof Set)) throw new IllegalArgumentException("Argument must implement java.util.Set"); if (!(d instanceof Set)) throw new IllegalArgumentException("Argument must implement java.util.Set"); this.addComposited(new Set[]{(Set) c, (Set) d}); } /** * Add an array of sets to this composite * * @param comps * @throws IllegalArgumentException if any of the collections15 in comps do not implement Set */ public synchronized void addComposited(Collection... comps) { for (int i = comps.length - 1; i >= 0; --i) { this.addComposited(comps[i]); } } /** * This can receive either a CompositeCollection.CollectionMutator * or a CompositeSet.SetMutator. If a * CompositeCollection.CollectionMutator is used than conflicts when adding * composited sets will throw IllegalArgumentException *

      */ public void setMutator(CollectionMutator mutator) { super.setMutator(mutator); } /* Set operations */ /** * If a CollectionMutator is defined for this CompositeSet then this * method will be called anyway. * * @param obj Object to be removed * @return true if the object is removed, false otherwise */ public boolean remove(Object obj) { for (Iterator i = this.getCollections().iterator(); i.hasNext();) { Set set = (Set) i.next(); if (set.contains(obj)) return set.remove(obj); } return false; } /** * @see Set#equals */ public boolean equals(Object obj) { if (obj instanceof Set) { Set set = (Set) obj; if (set.containsAll(this) && set.size() == this.size()) { return true; } } return false; } /** * @see Set#hashCode */ public int hashCode() { int code = 0; for (Iterator i = this.iterator(); i.hasNext();) { Object next = i.next(); code += (next != null ? next.hashCode() : 0); } return code; } /** * Define callbacks for mutation operations. *

      * Defining remove() on implementations of SetMutator is pointless * as they are never called by CompositeSet. */ public static interface SetMutator extends CompositeCollection.CollectionMutator { /** *

      * Called when a Set is added to the CompositeSet and there is a * collision between existing and added sets. *

      *

      * If added and existing still have any intersects * after this method returns an IllegalArgumentException will be thrown. *

      * * @param comp The CompositeSet being modified * @param existing The Set already existing in the composite * @param added the Set being added to the composite * @param intersects the intersection of th existing and added sets */ public void resolveCollision(CompositeSet comp, Set existing, Set added, Collection intersects); } } collections-generic-4.01/src/java/org/apache/commons/collections15/set/TransformedSortedSet.java0000644000175000017500000000746110464140762033246 0ustar giovannigiovanni// TODO: Not yet converted. /* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.set; import org.apache.commons.collections15.Transformer; import java.util.Comparator; import java.util.SortedSet; /** * Decorates another SortedSet to transform objects that are added. *

      * The add methods are affected by this class. * Thus objects must be removed or searched for using their transformed form. * For example, if the transformation converts Strings to Integers, you must * use the Integer form to remove objects. *

      * This class is Serializable from Commons Collections 3.1. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:39 $ * @since Commons Collections 3.0 */ public class TransformedSortedSet extends TransformedSet implements SortedSet { /** * Serialization version */ private static final long serialVersionUID = -1675486811351124386L; /** * Factory method to create a transforming sorted set. *

      * If there are any elements already in the set being decorated, they * are NOT transformed. * * @param set the set to decorate, must not be null * @param transformer the transformer to use for conversion, must not be null * @throws IllegalArgumentException if set or transformer is null */ public static SortedSet decorate(SortedSet set, Transformer transformer) { return new TransformedSortedSet(set, transformer); } //----------------------------------------------------------------------- /** * Constructor that wraps (not copies). *

      * If there are any elements already in the set being decorated, they * are NOT transformed. * * @param set the set to decorate, must not be null * @param transformer the transformer to use for conversion, must not be null * @throws IllegalArgumentException if set or transformer is null */ protected TransformedSortedSet(SortedSet set, Transformer transformer) { super(set, transformer); } /** * Gets the decorated set. * * @return the decorated set */ protected SortedSet getSortedSet() { return (SortedSet) collection; } //----------------------------------------------------------------------- public Object first() { return getSortedSet().first(); } public Object last() { return getSortedSet().last(); } public Comparator comparator() { return getSortedSet().comparator(); } //----------------------------------------------------------------------- public SortedSet subSet(Object fromElement, Object toElement) { SortedSet set = getSortedSet().subSet(fromElement, toElement); return new TransformedSortedSet(set, transformer); } public SortedSet headSet(Object toElement) { SortedSet set = getSortedSet().headSet(toElement); return new TransformedSortedSet(set, transformer); } public SortedSet tailSet(Object fromElement) { SortedSet set = getSortedSet().tailSet(fromElement); return new TransformedSortedSet(set, transformer); } } collections-generic-4.01/src/java/org/apache/commons/collections15/set/SynchronizedSortedSet.java0000644000175000017500000001016710464140756033441 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.set; import org.apache.commons.collections15.collection.SynchronizedCollection; import java.util.Comparator; import java.util.SortedSet; /** * Decorates another SortedSet to synchronize its behaviour * for a multi-threaded environment. *

      * Methods are synchronized, then forwarded to the decorated set. *

      * This class is Serializable from Commons Collections 3.1. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:39 $ * @since Commons Collections 3.0 */ public class SynchronizedSortedSet extends SynchronizedCollection implements SortedSet { /** * Serialization version */ private static final long serialVersionUID = 2775582861954500111L; /** * Factory method to create a synchronized set. * * @param set the set to decorate, must not be null * @throws IllegalArgumentException if set is null */ public static SortedSet decorate(SortedSet set) { return new SynchronizedSortedSet(set); } //----------------------------------------------------------------------- /** * Constructor that wraps (not copies). * * @param set the set to decorate, must not be null * @throws IllegalArgumentException if set is null */ protected SynchronizedSortedSet(SortedSet set) { super(set); } /** * Constructor that wraps (not copies). * * @param set the set to decorate, must not be null * @param lock the lock object to use, must not be null * @throws IllegalArgumentException if set is null */ protected SynchronizedSortedSet(SortedSet set, Object lock) { super(set, lock); } /** * Gets the decorated set. * * @return the decorated set */ protected SortedSet getSortedSet() { return (SortedSet) collection; } //----------------------------------------------------------------------- public SortedSet subSet(E fromElement, E toElement) { synchronized (lock) { SortedSet set = getSortedSet().subSet(fromElement, toElement); // the lock is passed into the constructor here to ensure that the // subset is synchronized on the same lock as the parent return new SynchronizedSortedSet(set, lock); } } public SortedSet headSet(E toElement) { synchronized (lock) { SortedSet set = getSortedSet().headSet(toElement); // the lock is passed into the constructor here to ensure that the // headset is synchronized on the same lock as the parent return new SynchronizedSortedSet(set, lock); } } public SortedSet tailSet(E fromElement) { synchronized (lock) { SortedSet set = getSortedSet().tailSet(fromElement); // the lock is passed into the constructor here to ensure that the // tailset is synchronized on the same lock as the parent return new SynchronizedSortedSet(set, lock); } } public E first() { synchronized (lock) { return getSortedSet().first(); } } public E last() { synchronized (lock) { return getSortedSet().last(); } } public Comparator comparator() { synchronized (lock) { return getSortedSet().comparator(); } } } collections-generic-4.01/src/java/org/apache/commons/collections15/set/ListOrderedSet.java0000644000175000017500000002313510464140760032013 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.set; import org.apache.commons.collections15.iterators.AbstractIteratorDecorator; import org.apache.commons.collections15.list.UnmodifiableList; import java.util.*; /** * Decorates another Set to ensure that the order of addition * is retained and used by the iterator. *

      * If an object is added to the set for a second time, it will remain in the * original position in the iteration. * The order can be observed from the set via the iterator or toArray methods. *

      * The ListOrderedSet also has various useful direct methods. These include many * from List, such as get(int), remove(int) * and indexOf(int). An unmodifiable List view of * the set can be obtained via asList(). *

      * This class cannot implement the List interface directly as * various interface methods (notably equals/hashCode) are incompatable with a set. *

      * This class is Serializable from Commons Collections 3.1. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @author Henning P. Schmiedehausen * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:39 $ * @since Commons Collections 3.0 */ public class ListOrderedSet extends AbstractSerializableSetDecorator implements Set { /** * Serialization version */ private static final long serialVersionUID = -228664372470420141L; /** * Internal list to hold the sequence of objects */ protected final List setOrder; /** * Factory method to create an ordered set specifying the list and set to use. * * @param set the set to decorate, must be empty and not null * @param list the list to decorate, must be empty and not null * @throws IllegalArgumentException if set or list is null * @throws IllegalArgumentException if either the set or list is not empty * @since Commons Collections 3.1 */ public static ListOrderedSet decorate(Set set, List list) { if (set == null) { throw new IllegalArgumentException("Set must not be null"); } if (list == null) { throw new IllegalArgumentException("List must not be null"); } if (set.size() > 0 || list.size() > 0) { throw new IllegalArgumentException("Set and List must be empty"); } return new ListOrderedSet(set, list); } /** * Factory method to create an ordered set. *

      * An ArrayList is used to retain order. * * @param set the set to decorate, must not be null * @throws IllegalArgumentException if set is null */ public static ListOrderedSet decorate(Set set) { return new ListOrderedSet(set); } /** * Factory method to create an ordered set using the supplied list to retain order. *

      * A HashSet is used for the set behaviour. * * @param list the list to decorate, must not be null * @throws IllegalArgumentException if list is null */ public static ListOrderedSet decorate(List list) { if (list == null) { throw new IllegalArgumentException("List must not be null"); } Set set = new HashSet(list); list.retainAll(set); return new ListOrderedSet(set, list); } //----------------------------------------------------------------------- /** * Constructs a new empty ListOrderedSet using * a HashSet and an ArrayList internally. * * @since Commons Collections 3.1 */ public ListOrderedSet() { super(new HashSet()); setOrder = new ArrayList(); } /** * Constructor that wraps (not copies). * * @param set the set to decorate, must not be null * @throws IllegalArgumentException if set is null */ protected ListOrderedSet(Set set) { super(set); setOrder = new ArrayList(set); } /** * Constructor that wraps (not copies) the Set and specifies the list to use. *

      * The set and list must both be correctly initialised to the same elements. * * @param set the set to decorate, must not be null * @param list the list to decorate, must not be null * @throws IllegalArgumentException if set or list is null */ protected ListOrderedSet(Set set, List list) { super(set); if (list == null) { throw new IllegalArgumentException("List must not be null"); } setOrder = list; } //----------------------------------------------------------------------- /** * Gets an unmodifiable view of the order of the Set. * * @return an unmodifiable list view */ public List asList() { return UnmodifiableList.decorate(setOrder); } //----------------------------------------------------------------------- public void clear() { collection.clear(); setOrder.clear(); } public Iterator iterator() { return new OrderedSetIterator(setOrder.iterator(), collection); } public boolean add(E object) { if (collection.contains(object)) { // re-adding doesn't change order return collection.add(object); } else { // first add, so add to both set and list boolean result = collection.add(object); setOrder.add(object); return result; } } public boolean addAll(Collection coll) { boolean result = false; for (Iterator it = coll.iterator(); it.hasNext();) { E object = it.next(); result = result | add(object); } return result; } public boolean remove(Object object) { boolean result = collection.remove(object); setOrder.remove(object); return result; } public boolean removeAll(Collection coll) { boolean result = false; for (Iterator it = coll.iterator(); it.hasNext();) { Object object = it.next(); result = result | remove(object); } return result; } public boolean retainAll(Collection coll) { boolean result = collection.retainAll(coll); if (result == false) { return false; } else if (collection.size() == 0) { setOrder.clear(); } else { for (Iterator it = setOrder.iterator(); it.hasNext();) { Object object = it.next(); if (collection.contains(object) == false) { it.remove(); } } } return result; } public Object[] toArray() { return setOrder.toArray(); } public T[] toArray(T[] a) { return setOrder.toArray(a); } //----------------------------------------------------------------------- public E get(int index) { return setOrder.get(index); } public int indexOf(E object) { return setOrder.indexOf(object); } public void add(int index, E object) { if (contains(object) == false) { collection.add(object); setOrder.add(index, object); } } public boolean addAll(int index, Collection coll) { boolean changed = false; for (Iterator it = coll.iterator(); it.hasNext();) { E object = it.next(); if (contains(object) == false) { collection.add(object); setOrder.add(index, object); index++; changed = true; } } return changed; } public E remove(int index) { E obj = setOrder.remove(index); remove(obj); return obj; } /** * Uses the underlying List's toString so that order is achieved. * This means that the decorated Set's toString is not used, so * any custom toStrings will be ignored. */ // Fortunately List.toString and Set.toString look the same public String toString() { return setOrder.toString(); } //----------------------------------------------------------------------- /** * Internal iterator handle remove. */ static class OrderedSetIterator extends AbstractIteratorDecorator { /** * Object we iterate on */ protected final Collection set; /** * Last object retrieved */ protected E last; private OrderedSetIterator(Iterator iterator, Collection set) { super(iterator); this.set = set; } public E next() { last = iterator.next(); return last; } public void remove() { set.remove(last); iterator.remove(); last = null; } } } collections-generic-4.01/src/java/org/apache/commons/collections15/set/package.html0000644000175000017500000000324210464140760030532 0ustar giovannigiovanni

      This package contains implementations of the {@link java.util.Set Set} and {@link java.util.SortedSet SortedSet} interfaces.

      The implementations are in the form of direct implementations and decorators. A decorator wraps another implementation of the interface to add some specific additional functionality.

      The following implementations are provided in the package:

      • CompositeSet - a set that combines multiple sets into one
      The following decorators are provided in the package:
      • Synchronized - synchronizes method access for multi-threaded environments
      • Unmodifiable - ensures the collection cannot be altered
      • Predicated - ensures that only elements that are valid according to a predicate can be added
      • Typed - ensures that only elements that are of a specific type can be added
      • Transformed - transforms each element added
      • ListOrdered - ensures that insertion order is retained
      • MapBackedSet - a set formed by decorating a Map
      collections-generic-4.01/src/java/org/apache/commons/collections15/Bag.java0000644000175000017500000002123210464140757027017 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15; import java.util.Collection; import java.util.Iterator; import java.util.Set; /** * Defines a collection that counts the number of times an object appears in * the collection. *

      * Suppose you have a Bag that contains {a, a, b, c}. * Calling {@link #getCount(Object)} on a would return 2, while * calling {@link #uniqueSet()} would return {a, b, c}. *

      * NOTE: This interface violates the {@link Collection} contract. * The behavior specified in many of these methods is not the same * as the behavior specified by Collection. * The noncompliant methods are clearly marked with "(Violation)". * Exercise caution when using a bag as a Collection. *

      * This violation resulted from the original specification of this interface. * In an ideal world, the interface would be changed to fix the problems, however * it has been decided to maintain backwards compatibility instead. * * @author Chuck Burdick * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:19 $ * @since Commons Collections 2.0 */ public interface Bag extends Collection { /** * Returns the number of occurrences (cardinality) of the given * object currently in the bag. If the object does not exist in the * bag, return 0. * * @param object the object to search for * @return the number of occurrences of the object, zero if not found */ int getCount(E object); /** * (Violation) * Adds one copy the specified object to the Bag. *

      * If the object is already in the {@link #uniqueSet()} then increment its * count as reported by {@link #getCount(Object)}. Otherwise add it to the * {@link #uniqueSet()} and report its count as 1. *

      * Since this method always increases the size of the bag, * according to the {@link Collection#add(Object)} contract, it * should always return true. Since it sometimes returns * false, this method violates the contract. * * @param object the object to add * @return true if the object was not already in the uniqueSet */ boolean add(E object); /** * Adds nCopies copies of the specified object to the Bag. *

      * If the object is already in the {@link #uniqueSet()} then increment its * count as reported by {@link #getCount(Object)}. Otherwise add it to the * {@link #uniqueSet()} and report its count as nCopies. * * @param object the object to add * @param nCopies the number of copies to add * @return true if the object was not already in the uniqueSet */ boolean add(E object, int nCopies); /** * (Violation) * Removes all occurrences of the given object from the bag. *

      * This will also remove the object from the {@link #uniqueSet()}. *

      * According to the {@link Collection#remove(Object)} method, * this method should only remove the first occurrence of the * given object, not all occurrences. * * @return true if this call changed the collection */ boolean remove(Object object); /** * Removes nCopies copies of the specified object from the Bag. *

      * If the number of copies to remove is greater than the actual number of * copies in the Bag, no error is thrown. * * @param object the object to remove * @param nCopies the number of copies to remove * @return true if this call changed the collection */ boolean remove(E object, int nCopies); /** * Returns a {@link Set} of unique elements in the Bag. *

      * Uniqueness constraints are the same as those in {@link java.util.Set}. * * @return the Set of unique Bag elements */ Set uniqueSet(); /** * Returns the total number of items in the bag across all types. * * @return the total size of the Bag */ int size(); /** * (Violation) * Returns true if the bag contains all elements in * the given collection, respecting cardinality. That is, if the * given collection coll contains n copies * of a given object, calling {@link #getCount(Object)} on that object must * be >= n for all n in coll. *

      * The {@link Collection#containsAll(Collection)} method specifies * that cardinality should not be respected; this method should * return true if the bag contains at least one of every object contained * in the given collection. * * @param coll the collection to check against * @return true if the Bag contains all the collection */ boolean containsAll(Collection coll); /** * (Violation) * Remove all elements represented in the given collection, * respecting cardinality. That is, if the given collection * coll contains n copies of a given object, * the bag will have n fewer copies, assuming the bag * had at least n copies to begin with. *

      *

      The {@link Collection#removeAll(Collection)} method specifies * that cardinality should not be respected; this method should * remove all occurrences of every object contained in the * given collection. * * @param coll the collection to remove * @return true if this call changed the collection */ boolean removeAll(Collection coll); /** * (Violation) * Remove any members of the bag that are not in the given * collection, respecting cardinality. That is, if the given * collection coll contains n copies of a * given object and the bag has m > n copies, then * delete m - n copies from the bag. In addition, if * e is an object in the bag but * !coll.contains(e), then remove e and any * of its copies. *

      *

      The {@link Collection#retainAll(Collection)} method specifies * that cardinality should not be respected; this method should * keep all occurrences of every object contained in the * given collection. * * @param coll the collection to retain * @return true if this call changed the collection */ boolean retainAll(Collection coll); /** * Returns an {@link Iterator} over the entire set of members, * including copies due to cardinality. This iterator is fail-fast * and will not tolerate concurrent modifications. * * @return iterator over all elements in the Bag */ Iterator iterator(); // The following is not part of the formal Bag interface, however where possible // Bag implementations should follow these comments. // /** // * Compares this Bag to another. // * This Bag equals another Bag if it contains the same number of occurrences of // * the same elements. // * This equals definition is compatible with the Set interface. // * // * @param obj the Bag to compare to // * @return true if equal // */ // boolean equals(Object obj); // // /** // * Gets a hash code for the Bag compatible with the definition of equals. // * The hash code is defined as the sum total of a hash code for each element. // * The per element hash code is defined as // * (e==null ? 0 : e.hashCode()) ^ noOccurances). // * This hash code definition is compatible with the Set interface. // * // * @return the hash code of the Bag // */ // int hashCode(); } collections-generic-4.01/src/java/org/apache/commons/collections15/KeyValue.java0000644000175000017500000000244710464140757030062 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15; /** * Defines a simple key value pair. *

      * A Map Entry has considerable additional semantics over and above a simple * key-value pair. This interface defines the minimum key value, with just the * two get methods. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:19 $ * @since Commons Collections 3.0 */ public interface KeyValue { /** * Gets the key from the pair. * * @return the key */ K getKey(); /** * Gets the value from the pair. * * @return the value */ V getValue(); } collections-generic-4.01/src/java/org/apache/commons/collections15/ListUtils.java0000644000175000017500000003124110464140757030263 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15; import org.apache.commons.collections15.list.*; import java.util.*; /** * Provides utility methods and decorators for {@link List} instances. * * @author Federico Barbieri * @author Peter Donald * @author Paul Jack * @author Stephen Colebourne * @author Neil O'Toole * @author Matt Hall, John Watkinson, Matthew Hawthorne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:19 $ * @since Commons Collections 1.0 */ public class ListUtils { /** * An empty unmodifiable list. * This uses the {@link Collections Collections} implementation * and is provided for completeness. */ public static final List EMPTY_LIST = Collections.EMPTY_LIST; /** * ListUtils should not normally be instantiated. */ public ListUtils() { } //----------------------------------------------------------------------- /** * Returns a new list containing all elements that are contained in * both given lists. * * @param list1 the first list * @param list2 the second list * @return the intersection of those two lists * @throws NullPointerException if either list is null */ public static List intersection(final List list1, final List list2) { final ArrayList result = new ArrayList(); final Iterator iterator = list2.iterator(); while (iterator.hasNext()) { final E o = iterator.next(); if (list1.contains(o)) { result.add(o); } } return result; } /** * Subtracts all elements in the second list from the first list, * placing the results in a new list. *

      * This differs from {@link List#removeAll(Collection)} in that * cardinality is respected; if list1 contains two * occurrences of null and list2 only * contains one occurrence, then the returned list will still contain * one occurrence. * * @param list1 the list to subtract from * @param list2 the list to subtract * @return a new list containing the results * @throws NullPointerException if either list is null */ public static List subtract(final List list1, final List list2) { final ArrayList result = new ArrayList(list1); final Iterator iterator = list2.iterator(); while (iterator.hasNext()) { result.remove(iterator.next()); } return result; } /** * Returns the sum of the given lists. This is their intersection * subtracted from their union. * * @param list1 the first list * @param list2 the second list * @return a new list containing the sum of those lists * @throws NullPointerException if either list is null */ public static List sum(final List list1, final List list2) { return subtract(union(list1, list2), intersection(list1, list2)); } /** * Returns a new list containing the second list appended to the * first list. The {@link List#addAll(Collection)} operation is * used to append the two given lists into a new list. * * @param list1 the first list * @param list2 the second list * @return a new list containing the union of those lists * @throws NullPointerException if either list is null */ public static List union(final List list1, final List list2) { final ArrayList result = new ArrayList(list1); result.addAll(list2); return result; } /** * Tests two lists for value-equality as per the equality contract in * {@link java.util.List#equals(java.lang.Object)}. *

      * This method is useful for implementing List when you cannot * extend AbstractList. The method takes Collection instances to enable other * collection types to use the List implementation algorithm. *

      * The relevant text (slightly paraphrased as this is a static method) is: *

      * Compares the two list objects for equality. Returns * true if and only if both * lists have the same size, and all corresponding pairs of elements in * the two lists are equal. (Two elements e1 and * e2 are equal if (e1==null ? e2==null : * e1.equals(e2)).) In other words, two lists are defined to be * equal if they contain the same elements in the same order. This * definition ensures that the equals method works properly across * different implementations of the List interface. *
      *

      * Note: The behaviour of this method is undefined if the lists are * modified during the equals comparison. * * @param list1 the first list, may be null * @param list2 the second list, may be null * @return whether the lists are equal by value comparison * @see java.util.List */ public static boolean isEqualList(final Collection list1, final Collection list2) { if (list1 == list2) { return true; } if (list1 == null || list2 == null || list1.size() != list2.size()) { return false; } Iterator it1 = list1.iterator(); Iterator it2 = list2.iterator(); E obj1 = null; E obj2 = null; while (it1.hasNext() && it2.hasNext()) { obj1 = it1.next(); obj2 = it2.next(); if (!(obj1 == null ? obj2 == null : obj1.equals(obj2))) { return false; } } return !(it1.hasNext() || it2.hasNext()); } /** * Generates a hash code using the algorithm specified in * {@link java.util.List#hashCode()}. *

      * This method is useful for implementing List when you cannot * extend AbstractList. The method takes Collection instances to enable other * collection types to use the List implementation algorithm. * * @param list the list to generate the hashCode for, may be null * @return the hash code * @see java.util.List#hashCode() */ public static int hashCodeForList(final Collection list) { if (list == null) { return 0; } int hashCode = 1; Iterator it = list.iterator(); Object obj = null; while (it.hasNext()) { obj = it.next(); hashCode = 31 * hashCode + (obj == null ? 0 : obj.hashCode()); } return hashCode; } //----------------------------------------------------------------------- /** * Returns a synchronized list backed by the given list. *

      * You must manually synchronize on the returned buffer's iterator to * avoid non-deterministic behavior: *

      *

           * List list = ListUtils.synchronizedList(myList);
           * synchronized (list) {
           *     Iterator i = list.iterator();
           *     while (i.hasNext()) {
           *         process (i.next());
           *     }
           * }
           * 
      *

      * This method uses the implementation in the decorators subpackage. * * @param list the list to synchronize, must not be null * @return a synchronized list backed by the given list * @throws IllegalArgumentException if the list is null */ public static List synchronizedList(List list) { return SynchronizedList.decorate(list); } /** * Returns an unmodifiable list backed by the given list. *

      * This method uses the implementation in the decorators subpackage. * * @param list the list to make unmodifiable, must not be null * @return an unmodifiable list backed by the given list * @throws IllegalArgumentException if the list is null */ public static List unmodifiableList(List list) { return UnmodifiableList.decorate(list); } /** * Returns a predicated (validating) list backed by the given list. *

      * Only objects that pass the test in the given predicate can be added to the list. * Trying to add an invalid object results in an IllegalArgumentException. * It is important not to use the original list after invoking this method, * as it is a backdoor for adding invalid objects. * * @param list the list to predicate, must not be null * @param predicate the predicate for the list, must not be null * @return a predicated list backed by the given list * @throws IllegalArgumentException if the List or Predicate is null */ public static List predicatedList(List list, Predicate predicate) { return PredicatedList.decorate(list, predicate); } /** * Returns a typed list backed by the given list. *

      * Only objects of the specified type can be added to the list. * * @param list the list to limit to a specific type, must not be null * @param type the type of objects which may be added to the list * @return a typed list backed by the specified list * @deprecated Java generics makes this method obsolete. */ public static List typedList(List list, Class type) { return TypedList.decorate(list, type); } /** * Returns a transformed list backed by the given list. *

      * Each object is passed through the transformer as it is added to the * List. It is important not to use the original list after invoking this * method, as it is a backdoor for adding untransformed objects. * * @param list the list to predicate, must not be null * @param transformer the transformer for the list, must not be null * @return a transformed list backed by the given list * @throws IllegalArgumentException if the List or Transformer is null */ public static List transformedList(List list, Transformer transformer) { return TransformedList.decorate(list, transformer); } /** * Returns a "lazy" list whose elements will be created on demand. *

      * When the index passed to the returned list's {@link List#get(int) get} * method is greater than the list's size, then the factory will be used * to create a new object and that object will be inserted at that index. *

      * For instance: *

      *

           * Factory factory = new Factory() {
           *     public Object create() {
           *         return new Date();
           *     }
           * }
           * List lazy = ListUtils.lazyList(new ArrayList(), factory);
           * Object obj = lazy.get(3);
           * 
      *

      * After the above code is executed, obj will contain * a new Date instance. Furthermore, that Date * instance is the fourth element in the list. The first, second, * and third element are all set to null. * * @param list the list to make lazy, must not be null * @param factory the factory for creating new objects, must not be null * @return a lazy list backed by the given list * @throws IllegalArgumentException if the List or Factory is null */ public static List lazyList(List list, Factory factory) { return LazyList.decorate(list, factory); } /** * Returns a fixed-sized list backed by the given list. * Elements may not be added or removed from the returned list, but * existing elements can be changed (for instance, via the * {@link List#set(int,Object)} method). * * @param list the list whose size to fix, must not be null * @return a fixed-size list backed by that list * @throws IllegalArgumentException if the List is null */ public static List fixedSizeList(List list) { return FixedSizeList.decorate(list); } } collections-generic-4.01/src/java/org/apache/commons/collections15/comparators/0000755000175000017500000000000011664401370030007 5ustar giovannigiovanni././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootcollections-generic-4.01/src/java/org/apache/commons/collections15/comparators/BooleanComparator.javacollections-generic-4.01/src/java/org/apache/commons/collections15/comparators/BooleanComparator.jav0000644000175000017500000001527610464140762034135 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.comparators; import java.io.Serializable; import java.util.Comparator; /** * A {@link Comparator} for {@link Boolean} objects that can sort either * true or false first. *

      * * @author Matt Hall, John Watkinson, Rodney Waldhoff * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:20 $ * @see #getTrueFirstComparator() * @see #getFalseFirstComparator() * @see #getBooleanComparator(boolean) * @since Commons Collections 3.0 */ public final class BooleanComparator implements Comparator, Serializable { /** * Serialization version. */ private static final long serialVersionUID = 1830042991606340609L; /** * Constant "true first" reference. */ private static final BooleanComparator TRUE_FIRST = new BooleanComparator(true); /** * Constant "false first" reference. */ private static final BooleanComparator FALSE_FIRST = new BooleanComparator(false); /** * true iff true values sort before false values. */ private boolean trueFirst = false; //----------------------------------------------------------------------- /** * Returns a BooleanComparator instance that sorts * true values before false values. *

      * Clients are encouraged to use the value returned from * this method instead of constructing a new instance * to reduce allocation and garbage collection overhead when * multiple BooleanComparators may be used in the same * virtual machine. * * @return the true first singleton BooleanComparator */ public static BooleanComparator getTrueFirstComparator() { return TRUE_FIRST; } /** * Returns a BooleanComparator instance that sorts * false values before true values. *

      * Clients are encouraged to use the value returned from * this method instead of constructing a new instance * to reduce allocation and garbage collection overhead when * multiple BooleanComparators may be used in the same * virtual machine. * * @return the false first singleton BooleanComparator */ public static BooleanComparator getFalseFirstComparator() { return FALSE_FIRST; } /** * Returns a BooleanComparator instance that sorts * trueFirst values before * !trueFirst values. *

      * Clients are encouraged to use the value returned from * this method instead of constructing a new instance * to reduce allocation and garbage collection overhead when * multiple BooleanComparators may be used in the same * virtual machine. * * @param trueFirst when true, sort * true Booleans before false * @return a singleton BooleanComparator instance */ public static BooleanComparator getBooleanComparator(boolean trueFirst) { return trueFirst ? TRUE_FIRST : FALSE_FIRST; } //----------------------------------------------------------------------- /** * Creates a BooleanComparator that sorts * false values before true values. *

      * Equivalent to {@link #BooleanComparator(boolean) BooleanComparator(false)}. *

      * Please use the static factory instead whenever possible. */ public BooleanComparator() { this(false); } /** * Creates a BooleanComparator that sorts * trueFirst values before * !trueFirst values. *

      * Please use the static factories instead whenever possible. * * @param trueFirst when true, sort * true boolean values before false */ public BooleanComparator(boolean trueFirst) { this.trueFirst = trueFirst; } /** * Compares two non-null Boolean objects * according to the value of {@link #trueFirst}. * * @param b1 the first boolean to compare * @param b2 the second boolean to compare * @return negative if obj1 is less, positive if greater, zero if equal * @throws NullPointerException when either argument null */ public int compare(Boolean b1, Boolean b2) { boolean v1 = b1.booleanValue(); boolean v2 = b2.booleanValue(); return (v1 ^ v2) ? ((v1 ^ trueFirst) ? 1 : -1) : 0; } //----------------------------------------------------------------------- /** * Implement a hash code for this comparator that is consistent with * {@link #equals(Object) equals}. * * @return a hash code for this comparator. */ public int hashCode() { int hash = "BooleanComparator".hashCode(); return trueFirst ? -1 * hash : hash; } /** * Returns true iff that Object is * is a {@link Comparator} whose ordering is known to be * equivalent to mine. *

      * This implementation returns true * iff that is a {@link BooleanComparator} * whose {@link #trueFirst} value is equal to mine. * * @param object the object to compare to * @return true if equal */ public boolean equals(Object object) { return (this == object) || ((object instanceof BooleanComparator) && (this.trueFirst == ((BooleanComparator) object).trueFirst)); } //----------------------------------------------------------------------- /** * Returns true iff * I sort true values before * false values. In other words, * returns true iff * {@link #compare(Boolean,Boolean) compare(Boolean.FALSE,Boolean.TRUE)} * returns a positive value. * * @return the trueFirst flag */ public boolean sortsTrueFirst() { return trueFirst; } } collections-generic-4.01/src/java/org/apache/commons/collections15/comparators/NullComparator.java0000644000175000017500000001404010464140756033620 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.comparators; import java.io.Serializable; import java.util.Comparator; /** * A Comparator that will compare nulls to be either lower or higher than * other objects. * * @author Matt Hall, John Watkinson, Michael A. Smith * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:20 $ * @since Commons Collections 2.0 */ public class NullComparator implements Comparator, Serializable { /** * Serialization version. */ private static final long serialVersionUID = -5820772575483504339L; /** * The comparator to use when comparing two non-null objects. */ private Comparator nonNullComparator; /** * Specifies whether a null are compared as higher than * non-null objects. */ private boolean nullsAreHigh; /** * Construct an instance that sorts null higher than any * non-null object it is compared with. When comparing two * non-null objects, the specified {@link Comparator} is * used. * * @param nonNullComparator the comparator to use when comparing two * non-null objects. This argument cannot be * null * @throws NullPointerException if nonNullComparator is * null */ public NullComparator(Comparator nonNullComparator) { this(nonNullComparator, true); } /** * Construct an instance that sorts null higher or lower than * any non-null object it is compared with. When comparing * two non-null objects, the specified {@link Comparator} is * used. * * @param nonNullComparator the comparator to use when comparing two * non-null objects. This argument cannot be * null * @param nullsAreHigh a true value indicates that * null should be compared as higher than a * non-null object. A false value indicates * that null should be compared as lower than a * non-null object. * @throws NullPointerException if nonNullComparator is * null */ public NullComparator(Comparator nonNullComparator, boolean nullsAreHigh) { this.nonNullComparator = nonNullComparator; this.nullsAreHigh = nullsAreHigh; if (nonNullComparator == null) { throw new NullPointerException("null nonNullComparator"); } } //----------------------------------------------------------------------- /** * Perform a comparison between two objects. If both objects are * null, a 0 value is returned. If one object * is null and the other is not, the result is determined on * whether the Comparator was constructed to have nulls as higher or lower * than other objects. If neither object is null, an * underlying comparator specified in the constructor (or the default) is * used to compare the non-null objects. * * @param o1 the first object to compare * @param o2 the object to compare it to. * @return -1 if o1 is "lower" than (less than, * before, etc.) o2; 1 if o1 is * "higher" than (greater than, after, etc.) o2; or * 0 if o1 and o2 are equal. */ public int compare(T o1, T o2) { if (o1 == o2) { return 0; } if (o1 == null) { return (this.nullsAreHigh ? 1 : -1); } if (o2 == null) { return (this.nullsAreHigh ? -1 : 1); } return this.nonNullComparator.compare(o1, o2); } //----------------------------------------------------------------------- /** * Implement a hash code for this comparator that is consistent with * {@link #equals(Object)}. * * @return a hash code for this comparator. */ public int hashCode() { return (nullsAreHigh ? -1 : 1) * nonNullComparator.hashCode(); } /** * Determines whether the specified object represents a comparator that is * equal to this comparator. * * @param obj the object to compare this comparator with. * @return true if the specified object is a NullComparator * with equivalent null comparison behavior * (i.e. null high or low) and with equivalent underlying * non-null object comparators. */ public boolean equals(Object obj) { if (obj == null) { return false; } if (obj == this) { return true; } if (!obj.getClass().equals(this.getClass())) { return false; } NullComparator other = (NullComparator) obj; return ((this.nullsAreHigh == other.nullsAreHigh) && (this.nonNullComparator.equals(other.nonNullComparator))); } } ././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootcollections-generic-4.01/src/java/org/apache/commons/collections15/comparators/TransformingComparator.javacollections-generic-4.01/src/java/org/apache/commons/collections15/comparators/TransformingComparato0000644000175000017500000000470210464140755034260 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.comparators; import org.apache.commons.collections15.Transformer; import java.util.Comparator; /** * Decorates another Comparator with transformation behavior. That is, the * return value from the transform operation will be passed to the decorated * {@link Comparator#compare(Object,Object) compare} method. * * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:20 $ * @see org.apache.commons.collections15.Transformer * @see org.apache.commons.collections15.comparators.ComparableComparator * @since Commons Collections 2.0 (?) */ public class TransformingComparator implements Comparator { /** * The decorated comparator. */ protected Comparator decorated; /** * The transformer being used. */ protected Transformer transformer; /** * Constructs an instance with the given Transformer and Comparator. * * @param transformer what will transform the arguments to compare * @param decorated the decorated Comparator */ public TransformingComparator(Transformer transformer, Comparator decorated) { this.decorated = decorated; this.transformer = transformer; } //----------------------------------------------------------------------- /** * Returns the result of comparing the values from the transform operation. * * @param obj1 the first object to transform then compare * @param obj2 the second object to transform then compare * @return negative if obj1 is less, positive if greater, zero if equal */ public int compare(I obj1, I obj2) { O value1 = this.transformer.transform(obj1); O value2 = this.transformer.transform(obj2); return this.decorated.compare(value1, value2); } } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootcollections-generic-4.01/src/java/org/apache/commons/collections15/comparators/ReverseComparator.javacollections-generic-4.01/src/java/org/apache/commons/collections15/comparators/ReverseComparator.jav0000644000175000017500000000720510464140760034160 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.comparators; import java.io.Serializable; import java.util.Comparator; /** * Reverses the order of another comparator by reversing the arguments * to its {@link #compare(Object, Object) compare} method. * * @author Henri Yandell * @author Matt Hall, John Watkinson, Michael A. Smith * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:20 $ * @see java.util.Collections#reverseOrder() * @since Commons Collections 2.0 */ public class ReverseComparator implements Comparator, Serializable { /** * Serialization version from Collections 2.0. */ private static final long serialVersionUID = 2858887242028539265L; /** * The comparator being decorated. */ private Comparator comparator; /** * Creates a comparator that inverts the comparison * of the given comparator. Pass in a {@link ComparableComparator} * for reversing the natural order, as per * {@link java.util.Collections#reverseOrder()}. * * @param comparator Comparator to reverse */ public ReverseComparator(Comparator comparator) { this.comparator = comparator; } //----------------------------------------------------------------------- /** * Compares two objects in reverse order. * * @param obj1 the first object to compare * @param obj2 the second object to compare * @return negative if obj1 is less, positive if greater, zero if equal */ public int compare(T obj1, T obj2) { return comparator.compare(obj2, obj1); } //----------------------------------------------------------------------- /** * Implement a hash code for this comparator that is consistent with * {@link #equals(Object) equals}. * * @return a suitable hash code * @since Commons Collections 3.0 */ public int hashCode() { return "ReverseComparator".hashCode() ^ comparator.hashCode(); } /** * Returns true iff that Object is * is a {@link Comparator} whose ordering is known to be * equivalent to mine. *

      * This implementation returns true * iff object.{@link Object#getClass() getClass()} * equals this.getClass(), and the underlying * comparators are equal. * Subclasses may want to override this behavior to remain consistent * with the {@link Comparator#equals(Object) equals} contract. * * @param object the object to compare to * @return true if equal * @since Commons Collections 3.0 */ public boolean equals(Object object) { if (this == object) { return true; } else if (null == object) { return false; } else if (object.getClass().equals(this.getClass())) { ReverseComparator thatrc = (ReverseComparator) object; return comparator.equals(thatrc.comparator); } else { return false; } } } ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootcollections-generic-4.01/src/java/org/apache/commons/collections15/comparators/FixedOrderComparator.javacollections-generic-4.01/src/java/org/apache/commons/collections15/comparators/FixedOrderComparator.0000644000175000017500000002421110464140765034100 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.comparators; import java.util.*; /** * A Comparator which imposes a specific order on a specific set of Objects. * Objects are presented to the FixedOrderComparator in a specified order and * subsequent calls to {@link #compare(Object, Object) compare} yield that order. * For example: *

       * String[] planets = {"Mercury", "Venus", "Earth", "Mars"};
       * FixedOrderComparator distanceFromSun = new FixedOrderComparator(planets);
       * Arrays.sort(planets);                     // Sort to alphabetical order
       * Arrays.sort(planets, distanceFromSun);    // Back to original order
       * 
      *

      * Once compare has been called, the FixedOrderComparator is locked * and attempts to modify it yield an UnsupportedOperationException. *

      * Instances of FixedOrderComparator are not synchronized. The class is not * thread-safe at construction time, but it is thread-safe to perform * multiple comparisons after all the setup operations are complete. * * @author David Leppik * @author Stephen Colebourne * @author Matt Hall, John Watkinson, Janek Bogucki * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:20 $ * @since Commons Collections 3.0 */ public class FixedOrderComparator implements Comparator { /** * Behavior when comparing unknown Objects: * unknown objects compare as before known Objects. */ public static final int UNKNOWN_BEFORE = 0; /** * Behavior when comparing unknown Objects: * unknown objects compare as after known Objects. */ public static final int UNKNOWN_AFTER = 1; /** * Behavior when comparing unknown Objects: * unknown objects cause a IllegalArgumentException to be thrown. * This is the default behavior. */ public static final int UNKNOWN_THROW_EXCEPTION = 2; /** * Internal map of object to position */ private final Map map = new HashMap(); /** * Counter used in determining the position in the map */ private int counter = 0; /** * Is the comparator locked against further change */ private boolean isLocked = false; /** * The behaviour in the case of an unknown object */ private int unknownObjectBehavior = UNKNOWN_THROW_EXCEPTION; // Constructors //----------------------------------------------------------------------- /** * Constructs an empty FixedOrderComparator. */ public FixedOrderComparator() { super(); } /** * Constructs a FixedOrderComparator which uses the order of the given array * to compare the objects. *

      * The array is copied, so later changes will not affect the comparator. * * @param items the items that the comparator can compare in order * @throws IllegalArgumentException if the array is null */ public FixedOrderComparator(T[] items) { super(); if (items == null) { throw new IllegalArgumentException("The list of items must not be null"); } for (int i = 0; i < items.length; i++) { add(items[i]); } } /** * Constructs a FixedOrderComparator which uses the order of the given list * to compare the objects. *

      * The list is copied, so later changes will not affect the comparator. * * @param items the items that the comparator can compare in order * @throws IllegalArgumentException if the list is null */ public FixedOrderComparator(List items) { super(); if (items == null) { throw new IllegalArgumentException("The list of items must not be null"); } for (Iterator it = items.iterator(); it.hasNext();) { add(it.next()); } } // Bean methods / state querying methods //----------------------------------------------------------------------- /** * Returns true if modifications cannot be made to the FixedOrderComparator. * FixedOrderComparators cannot be modified once they have performed a comparison. * * @return true if attempts to change the FixedOrderComparator yield an * UnsupportedOperationException, false if it can be changed. */ public boolean isLocked() { return isLocked; } /** * Checks to see whether the comparator is now locked against further changes. * * @throws UnsupportedOperationException if the comparator is locked */ protected void checkLocked() { if (isLocked()) { throw new UnsupportedOperationException("Cannot modify a FixedOrderComparator after a comparison"); } } /** * Gets the behavior for comparing unknown objects. * * @return the flag for unknown behaviour - UNKNOWN_AFTER, * UNKNOWN_BEFORE or UNKNOWN_THROW_EXCEPTION */ public int getUnknownObjectBehavior() { return unknownObjectBehavior; } /** * Sets the behavior for comparing unknown objects. * * @param unknownObjectBehavior the flag for unknown behaviour - * UNKNOWN_AFTER, UNKNOWN_BEFORE or UNKNOWN_THROW_EXCEPTION * @throws UnsupportedOperationException if a comparison has been performed * @throws IllegalArgumentException if the unknown flag is not valid */ public void setUnknownObjectBehavior(int unknownObjectBehavior) { checkLocked(); if (unknownObjectBehavior != UNKNOWN_AFTER && unknownObjectBehavior != UNKNOWN_BEFORE && unknownObjectBehavior != UNKNOWN_THROW_EXCEPTION) { throw new IllegalArgumentException("Unrecognised value for unknown behaviour flag"); } this.unknownObjectBehavior = unknownObjectBehavior; } // Methods for adding items //----------------------------------------------------------------------- /** * Adds an item, which compares as after all items known to the Comparator. * If the item is already known to the Comparator, its old position is * replaced with the new position. * * @param obj the item to be added to the Comparator. * @return true if obj has been added for the first time, false if * it was already known to the Comparator. * @throws UnsupportedOperationException if a comparison has already been made */ public boolean add(T obj) { checkLocked(); Integer position = map.put(obj, new Integer(counter++)); return (position == null); } /** * Adds a new item, which compares as equal to the given existing item. * * @param existingObj an item already in the Comparator's set of * known objects * @param newObj an item to be added to the Comparator's set of * known objects * @return true if newObj has been added for the first time, false if * it was already known to the Comparator. * @throws IllegalArgumentException if existingObject is not in the * Comparator's set of known objects. * @throws UnsupportedOperationException if a comparison has already been made */ public boolean addAsEqual(T existingObj, T newObj) { checkLocked(); Integer position = (Integer) map.get(existingObj); if (position == null) { throw new IllegalArgumentException(existingObj + " not known to " + this); } Integer result = map.put(newObj, position); return (result == null); } // Comparator methods //----------------------------------------------------------------------- /** * Compares two objects according to the order of this Comparator. *

      * It is important to note that this class will throw an IllegalArgumentException * in the case of an unrecognised object. This is not specified in the * Comparator interface, but is the most appropriate exception. * * @param obj1 the first object to compare * @param obj2 the second object to compare * @return negative if obj1 is less, positive if greater, zero if equal * @throws IllegalArgumentException if obj1 or obj2 are not known * to this Comparator and an alternative behavior has not been set * via {@link #setUnknownObjectBehavior(int)}. */ public int compare(T obj1, T obj2) { isLocked = true; Integer position1 = (Integer) map.get(obj1); Integer position2 = (Integer) map.get(obj2); if (position1 == null || position2 == null) { switch (unknownObjectBehavior) { case UNKNOWN_BEFORE: if (position1 == null) { return (position2 == null) ? 0 : -1; } else { return 1; } case UNKNOWN_AFTER: if (position1 == null) { return (position2 == null) ? 0 : 1; } else { return -1; } case UNKNOWN_THROW_EXCEPTION: Object unknownObj = (position1 == null) ? obj1 : obj2; throw new IllegalArgumentException("Attempting to compare unknown object " + unknownObj); default : throw new UnsupportedOperationException("Unknown unknownObjectBehavior: " + unknownObjectBehavior); } } else { return position1.compareTo(position2); } } } ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootcollections-generic-4.01/src/java/org/apache/commons/collections15/comparators/ComparableComparator.javacollections-generic-4.01/src/java/org/apache/commons/collections15/comparators/ComparableComparator.0000644000175000017500000001135610464140760034113 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.comparators; import java.io.Serializable; import java.util.Comparator; /** * A {@link Comparator Comparator} that compares * {@link Comparable Comparable} objects. *

      * This Comparator is useful, for example, * for enforcing the natural order in custom implementations * of SortedSet and SortedMap. *

      * Note: In the 2.0 and 2.1 releases of Commons Collections, * this class would throw a {@link ClassCastException} if * either of the arguments to {@link #compare(Object, Object) compare} * were null, not {@link Comparable Comparable}, * or for which {@link Comparable#compareTo(Object) compareTo} gave * inconsistent results. This is no longer the case. See * {@link #compare(Object, Object) compare} for details. * * @author Matt Hall, John Watkinson, Henri Yandell * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:20 $ * @see java.util.Collections#reverseOrder() * @since Commons Collections 2.0 */ public class ComparableComparator implements Comparator, Serializable { /** * Serialization version. */ private static final long serialVersionUID = -291439688585137865L; /** * The singleton instance. */ private static final ComparableComparator instance = new ComparableComparator(); //----------------------------------------------------------------------- /** * Gets the singleton instance of a ComparableComparator. *

      * Developers are encouraged to use the comparator returned from this method * instead of constructing a new instance to reduce allocation and GC overhead * when multiple comparable comparators may be used in the same VM. * * @return the singleton ComparableComparator */ public static Comparator getInstance() { return instance; } //----------------------------------------------------------------------- /** * Constructor whose use should be avoided. *

      * Please use the {@link #getInstance()} method whenever possible. */ public ComparableComparator() { super(); } //----------------------------------------------------------------------- /** * Compare the two {@link Comparable Comparable} arguments. * This method is equivalent to: *

      ((Comparable)obj1).compareTo(obj2)
      * * @param obj1 the first object to compare * @param obj2 the second object to compare * @return negative if obj1 is less, positive if greater, zero if equal * @throws NullPointerException when obj1 is null, * or when ((Comparable)obj1).compareTo(obj2) does * @throws ClassCastException when obj1 is not a Comparable, * or when ((Comparable)obj1).compareTo(obj2) does */ public int compare(T obj1, T obj2) { return obj1.compareTo(obj2); } //----------------------------------------------------------------------- /** * Implement a hash code for this comparator that is consistent with * {@link #equals(Object) equals}. * * @return a hash code for this comparator. * @since Commons Collections 3.0 */ public int hashCode() { return "ComparableComparator".hashCode(); } /** * Returns true iff that Object is * is a {@link Comparator Comparator} whose ordering is * known to be equivalent to mine. *

      * This implementation returns true * iff object.{@link Object#getClass() getClass()} * equals this.getClass(). * Subclasses may want to override this behavior to remain consistent * with the {@link Comparator#equals(Object)} contract. * * @param object the object to compare with * @return true if equal * @since Commons Collections 3.0 */ public boolean equals(Object object) { return (this == object) || ((null != object) && (object.getClass().equals(this.getClass()))); } } collections-generic-4.01/src/java/org/apache/commons/collections15/comparators/package.html0000644000175000017500000000176110464140755032301 0ustar giovannigiovanni

      This package contains implementations of the {@link java.util.Comparator Comparator} interface.

      You may also consider using {@link org.apache.commons.collections.ComparatorUtils ComparatorUtils}, which is a single class that uses static methods to construct instances of the classes in this package. collections-generic-4.01/src/java/org/apache/commons/collections15/comparators/ComparatorChain.java0000644000175000017500000002722510464140756033741 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 1999-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.comparators; import java.io.Serializable; import java.util.*; /** *

      A ComparatorChain is a Comparator that wraps one or * more Comparators in sequence. The ComparatorChain * calls each Comparator in sequence until either 1) * any single Comparator returns a non-zero result * (and that result is then returned), * or 2) the ComparatorChain is exhausted (and zero is * returned). This type of sorting is very similar * to multi-column sorting in SQL, and this class * allows Java classes to emulate that kind of behaviour * when sorting a List.

      *

      *

      To further facilitate SQL-like sorting, the order of * any single Comparator in the list can be reversed.

      *

      *

      Calling a method that adds new Comparators or * changes the ascend/descend sort after compare(Object, * Object) has been called will result in an * UnsupportedOperationException. However, take care * to not alter the underlying List of Comparators * or the BitSet that defines the sort order.

      *

      *

      Instances of ComparatorChain are not synchronized. * The class is not thread-safe at construction time, but * it is thread-safe to perform multiple comparisons * after all the setup operations are complete.

      * * @author Matt Hall, John Watkinson, Morgan Delagrange * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:20 $ * @since Commons Collections 2.0 */ public class ComparatorChain implements Comparator, Serializable { /** * Serialization version from Collections 2.0. */ private static final long serialVersionUID = -721644942746081630L; /** * The list of comparators in the chain. */ protected List> comparatorChain = null; /** * Order - false (clear) = ascend; true (set) = descend. */ protected BitSet orderingBits = null; /** * Whether the chain has been "locked". */ protected boolean isLocked = false; //----------------------------------------------------------------------- /** * Construct a ComparatorChain with no Comparators. * You must add at least one Comparator before calling * the compare(Object,Object) method, or an * UnsupportedOperationException is thrown */ public ComparatorChain() { this(new ArrayList>(), new BitSet()); } /** * Construct a ComparatorChain with a single Comparator, * sorting in the forward order * * @param comparator First comparator in the Comparator chain */ public ComparatorChain(Comparator comparator) { this(comparator, false); } /** * Construct a Comparator chain with a single Comparator, * sorting in the given order * * @param comparator First Comparator in the ComparatorChain * @param reverse false = forward sort; true = reverse sort */ public ComparatorChain(Comparator comparator, boolean reverse) { comparatorChain = new ArrayList>(); comparatorChain.add(comparator); orderingBits = new BitSet(1); if (reverse == true) { orderingBits.set(0); } } /** * Construct a ComparatorChain from the Comparators in the * List. All Comparators will default to the forward * sort order. * * @param list List of Comparators * @see #ComparatorChain(List,BitSet) */ public ComparatorChain(List> list) { this(list, new BitSet(list.size())); } /** * Construct a ComparatorChain from the Comparators in the * given List. The sort order of each column will be * drawn from the given BitSet. When determining the sort * order for Comparator at index i in the List, * the ComparatorChain will call BitSet.get(i). * If that method returns false, the forward * sort order is used; a return value of true * indicates reverse sort order. * * @param list List of Comparators. NOTE: This constructor does not perform a * defensive copy of the list * @param bits Sort order for each Comparator. Extra bits are ignored, * unless extra Comparators are added by another method. */ public ComparatorChain(List> list, BitSet bits) { comparatorChain = list; orderingBits = bits; } //----------------------------------------------------------------------- /** * Add a Comparator to the end of the chain using the * forward sort order * * @param comparator Comparator with the forward sort order */ public void addComparator(Comparator comparator) { addComparator(comparator, false); } /** * Add a Comparator to the end of the chain using the * given sort order * * @param comparator Comparator to add to the end of the chain * @param reverse false = forward sort order; true = reverse sort order */ public void addComparator(Comparator comparator, boolean reverse) { checkLocked(); comparatorChain.add(comparator); if (reverse == true) { orderingBits.set(comparatorChain.size() - 1); } } /** * Replace the Comparator at the given index, maintaining * the existing sort order. * * @param index index of the Comparator to replace * @param comparator Comparator to place at the given index * @throws IndexOutOfBoundsException if index < 0 or index >= size() */ public void setComparator(int index, Comparator comparator) throws IndexOutOfBoundsException { setComparator(index, comparator, false); } /** * Replace the Comparator at the given index in the * ComparatorChain, using the given sort order * * @param index index of the Comparator to replace * @param comparator Comparator to set * @param reverse false = forward sort order; true = reverse sort order */ public void setComparator(int index, Comparator comparator, boolean reverse) { checkLocked(); comparatorChain.set(index, comparator); if (reverse == true) { orderingBits.set(index); } else { orderingBits.clear(index); } } /** * Change the sort order at the given index in the * ComparatorChain to a forward sort. * * @param index Index of the ComparatorChain */ public void setForwardSort(int index) { checkLocked(); orderingBits.clear(index); } /** * Change the sort order at the given index in the * ComparatorChain to a reverse sort. * * @param index Index of the ComparatorChain */ public void setReverseSort(int index) { checkLocked(); orderingBits.set(index); } /** * Number of Comparators in the current ComparatorChain. * * @return Comparator count */ public int size() { return comparatorChain.size(); } /** * Determine if modifications can still be made to the * ComparatorChain. ComparatorChains cannot be modified * once they have performed a comparison. * * @return true = ComparatorChain cannot be modified; false = * ComparatorChain can still be modified. */ public boolean isLocked() { return isLocked; } // throw an exception if the ComparatorChain is locked private void checkLocked() { if (isLocked == true) { throw new UnsupportedOperationException("Comparator ordering cannot be changed after the first comparison is performed"); } } private void checkChainIntegrity() { if (comparatorChain.size() == 0) { throw new UnsupportedOperationException("ComparatorChains must contain at least one Comparator"); } } //----------------------------------------------------------------------- /** * Perform comparisons on the Objects as per * Comparator.compare(o1,o2). * * @param o1 the first object to compare * @param o2 the second object to compare * @return -1, 0, or 1 * @throws UnsupportedOperationException if the ComparatorChain does not contain at least one * Comparator */ public int compare(T o1, T o2) throws UnsupportedOperationException { if (isLocked == false) { checkChainIntegrity(); isLocked = true; } // iterate over all comparators in the chain Iterator> comparators = comparatorChain.iterator(); for (int comparatorIndex = 0; comparators.hasNext(); ++comparatorIndex) { Comparator comparator = comparators.next(); int retval = comparator.compare(o1, o2); if (retval != 0) { // invert the order if it is a reverse sort if (orderingBits.get(comparatorIndex) == true) { if (Integer.MIN_VALUE == retval) { retval = Integer.MAX_VALUE; } else { retval *= -1; } } return retval; } } // if comparators are exhausted, return 0 return 0; } //----------------------------------------------------------------------- /** * Implement a hash code for this comparator that is consistent with * {@link #equals(Object) equals}. * * @return a suitable hash code * @since Commons Collections 3.0 */ public int hashCode() { int hash = 0; if (null != comparatorChain) { hash ^= comparatorChain.hashCode(); } if (null != orderingBits) { hash ^= orderingBits.hashCode(); } return hash; } /** * Returns true iff that Object is * is a {@link Comparator} whose ordering is known to be * equivalent to mine. *

      * This implementation returns true * iff object.{@link Object#getClass() getClass()} * equals this.getClass(), and the underlying * comparators and order bits are equal. * Subclasses may want to override this behavior to remain consistent * with the {@link Comparator#equals(Object)} contract. * * @param object the object to compare with * @return true if equal * @since Commons Collections 3.0 */ public boolean equals(Object object) { if (this == object) { return true; } else if (null == object) { return false; } else if (object.getClass().equals(this.getClass())) { ComparatorChain chain = (ComparatorChain) object; return ((null == orderingBits ? null == chain.orderingBits : orderingBits.equals(chain.orderingBits)) && (null == comparatorChain ? null == chain.comparatorChain : comparatorChain.equals(chain.comparatorChain))); } else { return false; } } } collections-generic-4.01/src/java/org/apache/commons/collections15/OrderedMapIterator.java0000644000175000017500000000302310464140765032057 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15; /** * Defines an iterator that operates over an ordered Map. *

      * This iterator allows both forward and reverse iteration through the map. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:19 $ * @since Commons Collections 3.0 */ public interface OrderedMapIterator extends MapIterator, OrderedIterator { /** * Checks to see if there is a previous entry that can be iterated to. * * @return true if the iterator has a previous element */ boolean hasPrevious(); /** * Gets the previous key from the Map. * * @return the previous key in the iteration * @throws java.util.NoSuchElementException * if the iteration is finished */ K previous(); } collections-generic-4.01/src/java/org/apache/commons/collections15/OrderedMap.java0000644000175000017500000000472410464140757030357 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15; /** * Defines a map that maintains order and allows both forward and backward * iteration through that order. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:19 $ * @since Commons Collections 3.0 */ public interface OrderedMap extends IterableMap { /** * Obtains an OrderedMapIterator over the map. *

      * A ordered map iterator is an efficient way of iterating over maps * in both directions. *

           * BidiMap map = new TreeBidiMap();
           * MapIterator it = map.mapIterator();
           * while (it.hasNext()) {
           *   Object key = it.next();
           *   Object value = it.getValue();
           *   it.setValue("newValue");
           *   Object previousKey = it.previous();
           * }
           * 
      * * @return a map iterator */ OrderedMapIterator orderedMapIterator(); /** * Gets the first key currently in this map. * * @return the first key currently in this map * @throws java.util.NoSuchElementException * if this map is empty */ public K firstKey(); /** * Gets the last key currently in this map. * * @return the last key currently in this map * @throws java.util.NoSuchElementException * if this map is empty */ public K lastKey(); /** * Gets the next key after the one specified. * * @param key the key to search for next from * @return the next key, null if no match or at end */ public K nextKey(K key); /** * Gets the previous key before the one specified. * * @param key the key to search for previous from * @return the previous key, null if no match or at start */ public K previousKey(K key); } collections-generic-4.01/src/java/org/apache/commons/collections15/BufferUnderflowException.java0000644000175000017500000000427510464140763033311 0ustar giovannigiovanni// GenericsNote: No conversion necessary. /* * Copyright 2002-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15; import java.util.NoSuchElementException; /** * The BufferUnderflowException is used when the buffer is already empty. *

      * NOTE: From version 3.0, this exception extends NoSuchElementException. * * @author Avalon * @author Berin Loritsch * @author Jeff Turner * @author Paul Jack * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:19 $ * @since Commons Collections 2.1 */ public class BufferUnderflowException extends NoSuchElementException { /** * The root cause throwable */ private final Throwable throwable; /** * Constructs a new BufferUnderflowException. */ public BufferUnderflowException() { super(); throwable = null; } /** * Construct a new BufferUnderflowException. * * @param message the detail message for this exception */ public BufferUnderflowException(String message) { this(message, null); } /** * Construct a new BufferUnderflowException. * * @param message the detail message for this exception * @param exception the root cause of the exception */ public BufferUnderflowException(String message, Throwable exception) { super(message); throwable = exception; } /** * Gets the root cause of the exception. * * @return the root cause */ public final Throwable getCause() { return throwable; } } collections-generic-4.01/src/java/org/apache/commons/collections15/ComparatorUtils.java0000644000175000017500000002117310464140757031462 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2002-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15; import org.apache.commons.collections15.comparators.*; import java.util.Collection; import java.util.Comparator; /** * Provides convenient static utility methods for Comparator * objects. *

      * Most of the functionality in this class can also be found in the * comparators package. This class merely provides a * convenient central place if you have use for more than one class * in the comparators subpackage. * * @author Paul Jack * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:19 $ * @since Commons Collections 2.1 */ public class ComparatorUtils { /** * ComparatorUtils should not normally be instantiated. */ public ComparatorUtils() { } /** * Comparator for natural sort order. * * @see ComparableComparator#getInstance */ public static final Comparator NATURAL_COMPARATOR = ComparableComparator.getInstance(); /** * Gets a comparator that uses the natural order of the objects. * * @return a comparator which uses natural order */ public static Comparator naturalComparator() { return NATURAL_COMPARATOR; } /** * Gets a comparator that compares using two {@link Comparator}s. *

      * The second comparator is used if the first comparator returns equal. * * @param comparator1 the first comparator to use, not null * @param comparator2 the first comparator to use, not null * @return a {@link ComparatorChain} formed from the two comparators * @throws NullPointerException if either comparator is null * @see ComparatorChain */ public static Comparator chainedComparator(Comparator comparator1, Comparator comparator2) { return chainedComparator(new Comparator[]{comparator1, comparator2}); } /** * Gets a comparator that compares using an array of {@link Comparator}s, applied * in sequence until one returns not equal or the array is exhausted. * * @param comparators the comparators to use, not null or empty or containing nulls * @return a {@link ComparatorChain} formed from the input comparators * @throws NullPointerException if comparators array is null or contains a null * @see ComparatorChain */ public static Comparator chainedComparator(Comparator[] comparators) { ComparatorChain chain = new ComparatorChain(); for (int i = 0; i < comparators.length; i++) { if (comparators[i] == null) { throw new NullPointerException("Comparator cannot be null"); } chain.addComparator(comparators[i]); } return chain; } /** * Gets a comparator that compares using a collection of {@link Comparator}s, * applied in (default iterator) sequence until one returns not equal or the * collection is exhausted. * * @param comparators the comparators to use, not null or empty or containing nulls * @return a {@link ComparatorChain} formed from the input comparators * @throws NullPointerException if comparators collection is null or contains a null * @throws ClassCastException if the comparators collection contains the wrong object type * @see ComparatorChain */ public static Comparator chainedComparator(Collection comparators) { return chainedComparator((Comparator[]) comparators.toArray(new Comparator[comparators.size()])); } /** * Gets a comparator that reverses the order of the given comparator. * * @param comparator the comparator to reverse * @return a comparator that reverses the order of the input comparator * @see ReverseComparator */ public static Comparator reversedComparator(Comparator comparator) { if (comparator == null) { comparator = NATURAL_COMPARATOR; } return new ReverseComparator(comparator); } /** * Gets a Comparator that can sort Boolean objects. *

      * The parameter specifies whether true or false is sorted first. *

      * The comparator throws NullPointerException if a null value is compared. * * @param trueFirst when true, sort * true {@link Boolean}s before * false {@link Boolean}s. * @return a comparator that sorts booleans */ public static Comparator booleanComparator(boolean trueFirst) { return BooleanComparator.getBooleanComparator(trueFirst); } /** * Gets a Comparator that controls the comparison of null values. *

      * The returned comparator will consider a null value to be less than * any nonnull value, and equal to any other null value. Two nonnull * values will be evaluated with the given comparator. * * @param comparator the comparator that wants to allow nulls * @return a version of that comparator that allows nulls * @see NullComparator */ public static Comparator nullLowComparator(Comparator comparator) { if (comparator == null) { comparator = NATURAL_COMPARATOR; } return new NullComparator(comparator, false); } /** * Gets a Comparator that controls the comparison of null values. *

      * The returned comparator will consider a null value to be greater than * any nonnull value, and equal to any other null value. Two nonnull * values will be evaluated with the given comparator. * * @param comparator the comparator that wants to allow nulls * @return a version of that comparator that allows nulls * @see NullComparator */ public static Comparator nullHighComparator(Comparator comparator) { if (comparator == null) { comparator = NATURAL_COMPARATOR; } return new NullComparator(comparator, true); } /** * Gets a Comparator that passes transformed objects to the given comparator. *

      * Objects passed to the returned comparator will first be transformed * by the given transformer before they are compared by the given * comparator. * * @param comparator the sort order to use * @param transformer the transformer to use * @return a comparator that transforms its input objects before comparing them * @see TransformingComparator */ public static Comparator transformedComparator(Comparator comparator, Transformer transformer) { if (comparator == null) { comparator = NATURAL_COMPARATOR; } return new TransformingComparator(transformer, comparator); } /** * Returns the smaller of the given objects according to the given * comparator, returning the second object if the comparator * returns equal. * * @param o1 the first object to compare * @param o2 the second object to compare * @param comparator the sort order to use * @return the smaller of the two objects */ public static T min(T o1, T o2, Comparator comparator) { if (comparator == null) { comparator = NATURAL_COMPARATOR; } int c = comparator.compare(o1, o2); return (c < 0) ? o1 : o2; } /** * Returns the larger of the given objects according to the given * comparator, returning the second object if the comparator * returns equal. * * @param o1 the first object to compare * @param o2 the second object to compare * @param comparator the sort order to use * @return the larger of the two objects */ public static T max(T o1, T o2, Comparator comparator) { if (comparator == null) { comparator = NATURAL_COMPARATOR; } int c = comparator.compare(o1, o2); return (c > 0) ? o1 : o2; } } collections-generic-4.01/src/java/org/apache/commons/collections15/Buffer.java0000644000175000017500000000437310464140756027545 0ustar giovannigiovanni// // GenericsNote: Converted. /* * Copyright 2002-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15; import java.util.Collection; /** * Defines a collection that allows objects to be removed in some well-defined order. *

      * The removal order can be based on insertion order (eg, a FIFO queue or a * LIFO stack), on access order (eg, an LRU cache), on some arbitrary comparator * (eg, a priority queue) or on any other well-defined ordering. *

      * Note that the removal order is not necessarily the same as the iteration * order. A Buffer implementation may have equivalent removal * and iteration orders, but this is not required. *

      * This interface does not specify any behavior for * {@link Object#equals(Object)} and {@link Object#hashCode} methods. It * is therefore possible for a Buffer implementation to also * also implement {@link java.util.List}, {@link java.util.Set} or * {@link Bag}. * * @author Avalon * @author Berin Loritsch * @author Paul Jack * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:19 $ * @since Commons Collections 2.1 */ public interface Buffer extends Collection { /** * Gets and removes the next object from the buffer. * * @return the next object in the buffer, which is also removed * @throws BufferUnderflowException if the buffer is already empty */ E remove(); /** * Gets the next object from the buffer without removing it. * * @return the next object in the buffer, which is not removed * @throws BufferUnderflowException if the buffer is empty */ E get(); } collections-generic-4.01/src/java/org/apache/commons/collections15/BufferUtils.java0000644000175000017500000001274410464140757030570 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2002-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15; import org.apache.commons.collections15.buffer.*; /** * Provides utility methods and decorators for {@link Buffer} instances. * * @author Matt Hall, John Watkinson, Paul Jack * @author Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:19 $ * @since Commons Collections 2.1 */ public class BufferUtils { /** * An empty unmodifiable buffer. */ public static final Buffer EMPTY_BUFFER = UnmodifiableBuffer.decorate(new ArrayStack(1)); /** * BufferUtils should not normally be instantiated. */ public BufferUtils() { } //----------------------------------------------------------------------- /** * Returns a synchronized buffer backed by the given buffer. * Much like the synchronized collections15 returned by * {@link java.util.Collections}, you must manually synchronize on * the returned buffer's iterator to avoid non-deterministic behavior: *

      *

           * Buffer b = BufferUtils.synchronizedBuffer(myBuffer);
           * synchronized (b) {
           *     Iterator i = b.iterator();
           *     while (i.hasNext()) {
           *         process (i.next());
           *     }
           * }
           * 
      * * @param buffer the buffer to synchronize, must not be null * @return a synchronized buffer backed by that buffer * @throws IllegalArgumentException if the Buffer is null */ public static Buffer synchronizedBuffer(Buffer buffer) { return SynchronizedBuffer.decorate(buffer); } /** * Returns a synchronized buffer backed by the given buffer that will * block on {@link Buffer#get()} and {@link Buffer#remove()} operations. * If the buffer is empty, then the {@link Buffer#get()} and * {@link Buffer#remove()} operations will block until new elements * are added to the buffer, rather than immediately throwing a * BufferUnderflowException. * * @param buffer the buffer to synchronize, must not be null * @return a blocking buffer backed by that buffer * @throws IllegalArgumentException if the Buffer is null */ public static Buffer blockingBuffer(Buffer buffer) { return BlockingBuffer.decorate(buffer); } /** * Returns an unmodifiable buffer backed by the given buffer. * * @param buffer the buffer to make unmodifiable, must not be null * @return an unmodifiable buffer backed by that buffer * @throws IllegalArgumentException if the Buffer is null */ public static Buffer unmodifiableBuffer(Buffer buffer) { return UnmodifiableBuffer.decorate(buffer); } /** * Returns a predicated (validating) buffer backed by the given buffer. *

      * Only objects that pass the test in the given predicate can be added to the buffer. * Trying to add an invalid object results in an IllegalArgumentException. * It is important not to use the original buffer after invoking this method, * as it is a backdoor for adding invalid objects. * * @param buffer the buffer to predicate, must not be null * @param predicate the predicate used to evaluate new elements, must not be null * @return a predicated buffer * @throws IllegalArgumentException if the Buffer or Predicate is null */ public static Buffer predicatedBuffer(Buffer buffer, Predicate predicate) { return PredicatedBuffer.decorate(buffer, predicate); } /** * Returns a typed buffer backed by the given buffer. *

      * Only elements of the specified type can be added to the buffer. * * @param buffer the buffer to predicate, must not be null * @param type the type to allow into the buffer, must not be null * @return a typed buffer * @throws IllegalArgumentException if the buffer or type is null * @deprecated No longer required with Java 1.5 Generics. */ public static Buffer typedBuffer(Buffer buffer, Class type) { return TypedBuffer.decorate(buffer, type); } /** * Returns a transformed buffer backed by the given buffer. *

      * Each object is passed through the transformer as it is added to the * Buffer. It is important not to use the original buffer after invoking this * method, as it is a backdoor for adding untransformed objects. * * @param buffer the buffer to predicate, must not be null * @param transformer the transformer for the buffer, must not be null * @return a transformed buffer backed by the given buffer * @throws IllegalArgumentException if the Buffer or Transformer is null */ public static Buffer transformedBuffer(Buffer buffer, Transformer transformer) { return TransformedBuffer.decorate(buffer, transformer); } } collections-generic-4.01/src/java/org/apache/commons/collections15/Factory.java0000644000175000017500000000277710464140757027752 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2002-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15; /** * Defines a functor interface implemented by classes that create objects. *

      * A Factory creates an object without using an input parameter. * If an input parameter is required, then {@link Transformer} is more appropriate. *

      * Standard implementations of common factories are provided by * {@link FactoryUtils}. These include factories that return a constant, * a copy of a prototype or a new instance. * * @author Arron Bates * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:19 $ * @since Commons Collections 2.1 */ public interface Factory { /** * Create a new object. * * @return a new object * @throws FunctorException (runtime) if the factory cannot create an object */ public T create(); } collections-generic-4.01/src/java/org/apache/commons/collections15/OrderedBidiMap.java0000644000175000017500000000473610464140755031150 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15; /** * Defines a map that allows bidirectional lookup between key and values * and retains and provides access to an ordering. *

      * Implementations should allow a value to be looked up from a key and * a key to be looked up from a value with equal performance. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:19 $ * @since Commons Collections 3.0 */ public interface OrderedBidiMap extends BidiMap, OrderedMap { /** * Gets a view of this map where the keys and values are reversed. *

      * Changes to one map will be visible in the other and vice versa. * This enables both directions of the map to be accessed equally. *

      * Implementations should seek to avoid creating a new object every time this * method is called. See AbstractMap.values() etc. Calling this * method on the inverse map should return the original. *

      * Implementations must return an OrderedBidiMap instance, * usually by forwarding to inverseOrderedBidiMap(). * * @return an inverted bidirectional map */ public BidiMap inverseBidiMap(); /** * Gets a view of this map where the keys and values are reversed. *

      * Changes to one map will be visible in the other and vice versa. * This enables both directions of the map to be accessed equally. *

      * Implementations should seek to avoid creating a new object every time this * method is called. See AbstractMap.values() etc. Calling this * method on the inverse map should return the original. * * @return an inverted bidirectional map */ public OrderedBidiMap inverseOrderedBidiMap(); } collections-generic-4.01/src/java/org/apache/commons/collections15/overview.html0000644000175000017500000000731610464140763030223 0ustar giovannigiovanni

      Commons-Collections contains implementations, enhancements and utilities that complement the Java Collections Framework.

      The Apache Jakarta Commons Collections Framework component adds a significant amount of enhancements to the standard JDK collections. These enhancements come in the form of new interfaces, new implementations and utility classes.

      See also the java.util package for the standard Java collections.

      Main features

      Commons-Collections defines a number of key interfaces:

      InterfaceDescription
      {@link org.apache.commons.collections.Bag} A new Collection subinterface that stores each object together with the number of occurances. Methods are provided to get the number of occurances, and to add and remove a certain number of that object.
      {@link org.apache.commons.collections.Buffer} A new Collection subinterface that allows objects to be removed in some well-defined order. Methods enable the next item to be peeked and removed.
      {@link org.apache.commons.collections.BidiMap} A new Map subinterface that allows lookup from key to value and from value to key with equal ease.
      {@link org.apache.commons.collections.OrderedMap} A new Map subinterface that is used when a map has an order, but is not sorted. Methods enable bidriectional iteration through the map.
      {@link org.apache.commons.collections.MapIterator} A new Iterator subinterface specially designed for maps. This iterator avoids the need for entrySet iteration of a map, and is simpler to use.
      {@link org.apache.commons.collections.ResettableIterator} A new Iterator subinterface that allows the iteration to be reset back to the start. Many iterators in this library have this functionality.
      {@link org.apache.commons.collections.Closure}
      {@link org.apache.commons.collections.Predicate}
      {@link org.apache.commons.collections.Transformer}
      {@link org.apache.commons.collections.Factory}
      A group of functor interfaces that provide plugin behaviour to various collections and utilities.

      In addition to the interfaces, there are many implementations. Consult each subpackage for full details of these.

      collections-generic-4.01/src/java/org/apache/commons/collections15/BagUtils.java0000644000175000017500000002223210464140757030041 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2002-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15; import org.apache.commons.collections15.bag.*; /** * Provides utility methods and decorators for * {@link Bag} and {@link SortedBag} instances. * * @author Paul Jack * @author Stephen Colebourne * @author Andrew Freeman * @author Matt Hall, John Watkinson, Matthew Hawthorne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:19 $ * @since Commons Collections 2.1 */ public class BagUtils { /** * An empty unmodifiable bag. */ public static final Bag EMPTY_BAG = UnmodifiableBag.decorate(new HashBag()); /** * An empty unmodifiable sorted bag. */ public static final Bag EMPTY_SORTED_BAG = UnmodifiableSortedBag.decorate(new TreeBag()); /** * Instantiation of BagUtils is not intended or required. * However, some tools require an instance to operate. */ public BagUtils() { } //----------------------------------------------------------------------- /** * Returns a synchronized (thread-safe) bag backed by the given bag. * In order to guarantee serial access, it is critical that all * access to the backing bag is accomplished through the returned bag. *

      * It is imperative that the user manually synchronize on the returned * bag when iterating over it: *

      *

           * Bag bag = BagUtils.synchronizedBag(new HashBag());
           * ...
           * synchronized(bag) {
           *     Iterator i = bag.iterator(); // Must be in synchronized block
           *     while (i.hasNext())
           *         foo(i.next());
           *     }
           * }
           * 
      *

      * Failure to follow this advice may result in non-deterministic * behavior. * * @param bag the bag to synchronize, must not be null * @return a synchronized bag backed by that bag * @throws IllegalArgumentException if the Bag is null */ public static Bag synchronizedBag(Bag bag) { return SynchronizedBag.decorate(bag); } /** * Returns an unmodifiable view of the given bag. Any modification * attempts to the returned bag will raise an * {@link UnsupportedOperationException}. * * @param bag the bag whose unmodifiable view is to be returned, must not be null * @return an unmodifiable view of that bag * @throws IllegalArgumentException if the Bag is null */ public static Bag unmodifiableBag(Bag bag) { return UnmodifiableBag.decorate(bag); } /** * Returns a predicated (validating) bag backed by the given bag. *

      * Only objects that pass the test in the given predicate can be added to the bag. * Trying to add an invalid object results in an IllegalArgumentException. * It is important not to use the original bag after invoking this method, * as it is a backdoor for adding invalid objects. * * @param bag the bag to predicate, must not be null * @param predicate the predicate for the bag, must not be null * @return a predicated bag backed by the given bag * @throws IllegalArgumentException if the Bag or Predicate is null */ public static Bag predicatedBag(Bag bag, Predicate predicate) { return PredicatedBag.decorate(bag, predicate); } /** * Returns a typed bag backed by the given bag. *

      * Only objects of the specified type can be added to the bag. * * @param bag the bag to limit to a specific type, must not be null * @param type the type of objects which may be added to the bag * @return a typed bag backed by the specified bag * @deprecated Java 1.5 generics makes this method no longer useful. */ public static Bag typedBag(Bag bag, Class type) { return TypedBag.decorate(bag, type); } /** * Returns a transformed bag backed by the given bag. *

      * Each object is passed through the transformer as it is added to the * Bag. It is important not to use the original bag after invoking this * method, as it is a backdoor for adding untransformed objects. * * @param bag the bag to predicate, must not be null * @param transformer the transformer for the bag, must not be null * @return a transformed bag backed by the given bag * @throws IllegalArgumentException if the Bag or Transformer is null * @deprecated TransformedCollections are not type-safe in Java 1.5. */ public static Bag transformedBag(Bag bag, Transformer transformer) { return TransformedBag.decorate(bag, transformer); } //----------------------------------------------------------------------- /** * Returns a synchronized (thread-safe) sorted bag backed by the given * sorted bag. * In order to guarantee serial access, it is critical that all * access to the backing bag is accomplished through the returned bag. *

      * It is imperative that the user manually synchronize on the returned * bag when iterating over it: *

      *

           * SortedBag bag = BagUtils.synchronizedSortedBag(new TreeBag());
           * ...
           * synchronized(bag) {
           *     Iterator i = bag.iterator(); // Must be in synchronized block
           *     while (i.hasNext())
           *         foo(i.next());
           *     }
           * }
           * 
      *

      * Failure to follow this advice may result in non-deterministic * behavior. * * @param bag the bag to synchronize, must not be null * @return a synchronized bag backed by that bag * @throws IllegalArgumentException if the SortedBag is null */ public static SortedBag synchronizedSortedBag(SortedBag bag) { return SynchronizedSortedBag.decorate(bag); } /** * Returns an unmodifiable view of the given sorted bag. Any modification * attempts to the returned bag will raise an * {@link UnsupportedOperationException}. * * @param bag the bag whose unmodifiable view is to be returned, must not be null * @return an unmodifiable view of that bag * @throws IllegalArgumentException if the SortedBag is null */ public static SortedBag unmodifiableSortedBag(SortedBag bag) { return UnmodifiableSortedBag.decorate(bag); } /** * Returns a predicated (validating) sorted bag backed by the given sorted bag. *

      * Only objects that pass the test in the given predicate can be added to the bag. * Trying to add an invalid object results in an IllegalArgumentException. * It is important not to use the original bag after invoking this method, * as it is a backdoor for adding invalid objects. * * @param bag the sorted bag to predicate, must not be null * @param predicate the predicate for the bag, must not be null * @return a predicated bag backed by the given bag * @throws IllegalArgumentException if the SortedBag or Predicate is null */ public static SortedBag predicatedSortedBag(SortedBag bag, Predicate predicate) { return PredicatedSortedBag.decorate(bag, predicate); } /** * Returns a typed sorted bag backed by the given bag. *

      * Only objects of the specified type can be added to the bag. * * @param bag the bag to limit to a specific type, must not be null * @param type the type of objects which may be added to the bag * @return a typed bag backed by the specified bag * @deprecated Java 1.5 generics makes this method no longer useful. */ public static SortedBag typedSortedBag(SortedBag bag, Class type) { return TypedSortedBag.decorate(bag, type); } /** * Returns a transformed sorted bag backed by the given bag. *

      * Each object is passed through the transformer as it is added to the * Bag. It is important not to use the original bag after invoking this * method, as it is a backdoor for adding untransformed objects. * * @param bag the bag to predicate, must not be null * @param transformer the transformer for the bag, must not be null * @return a transformed bag backed by the given bag * @throws IllegalArgumentException if the Bag or Transformer is null * @deprecated This breaks the java.util.Collection interface in Java 1.5. It is recommended that it not be used. */ public static SortedBag transformedSortedBag(SortedBag bag, Transformer transformer) { return TransformedSortedBag.decorate(bag, transformer); } } collections-generic-4.01/src/java/org/apache/commons/collections15/list/0000755000175000017500000000000011664401370026430 5ustar giovannigiovannicollections-generic-4.01/src/java/org/apache/commons/collections15/list/CursorableLinkedList.java0000644000175000017500000004302610464140756033371 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2002-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.list; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.lang.ref.WeakReference; import java.util.*; /** * A List implementation with a ListIterator that * allows concurrent modifications to the underlying list. *

      * This implementation supports all of the optional {@link List} operations. * It extends AbstractLinkedList and thus provides the * stack/queue/dequeue operations available in {@link java.util.LinkedList}. *

      * The main feature of this class is the ability to modify the list and the * iterator at the same time. Both the {@link #listIterator()} and {@link #cursor()} * methods provides access to a Cursor instance which extends * ListIterator. The cursor allows changes to the list concurrent * with changes to the iterator. Note that the {@link #iterator()} method and * sublists do not provide this cursor behaviour. *

      * The Cursor class is provided partly for backwards compatibility * and partly because it allows the cursor to be directly closed. Closing the * cursor is optional because references are held via a WeakReference. * For most purposes, simply modify the iterator and list at will, and then let * the garbage collector to the rest. *

      * Note that this implementation is not synchronized. * * @author Rodney Waldhoff * @author Janek Bogucki * @author Simon Kitching * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:32 $ * @see java.util.LinkedList * @since Commons Collections 1.0 */ public class CursorableLinkedList extends AbstractLinkedList implements Serializable { /** * Ensure serialization compatibility */ private static final long serialVersionUID = 8836393098519411393L; /** * A list of the cursor currently open on this list */ protected transient List>> cursors = new ArrayList>>(); //----------------------------------------------------------------------- /** * Constructor that creates. */ public CursorableLinkedList() { super(); init(); // must call init() as use super(); } /** * Constructor that copies the specified collection * * @param coll the collection to copy */ public CursorableLinkedList(Collection coll) { super(coll); } /** * The equivalent of a default constructor called * by any constructor and by readObject. */ protected void init() { super.init(); cursors = new ArrayList>>(); } //----------------------------------------------------------------------- /** * Returns an iterator that does not support concurrent modification. *

      * If the underlying list is modified while iterating using this iterator * a ConcurrentModificationException will occur. * The cursor behaviour is available via {@link #listIterator()}. * * @return a new iterator that does not support concurrent modification */ public Iterator iterator() { return super.listIterator(0); } /** * Returns a cursor iterator that allows changes to the underlying list in parallel. *

      * The cursor enables iteration and list changes to occur in any order without * invalidating the iterator (from one thread). When elements are added to the * list, an event is fired to all active cursors enabling them to adjust to the * change in the list. *

      * When the "current" (i.e., last returned by {@link ListIterator#next} * or {@link ListIterator#previous}) element of the list is removed, * the cursor automatically adjusts to the change (invalidating the * last returned value such that it cannot be removed). * * @return a new cursor iterator */ public ListIterator listIterator() { return cursor(0); } /** * Returns a cursor iterator that allows changes to the underlying list in parallel. *

      * The cursor enables iteration and list changes to occur in any order without * invalidating the iterator (from one thread). When elements are added to the * list, an event is fired to all active cursors enabling them to adjust to the * change in the list. *

      * When the "current" (i.e., last returned by {@link ListIterator#next} * or {@link ListIterator#previous}) element of the list is removed, * the cursor automatically adjusts to the change (invalidating the * last returned value such that it cannot be removed). * * @param fromIndex the index to start from * @return a new cursor iterator */ public ListIterator listIterator(int fromIndex) { return cursor(fromIndex); } /** * Returns a {@link Cursor} for iterating through the elements of this list. *

      * A Cursor is a ListIterator with an additional * close() method. Calling this method immediately discards the * references to the cursor. If it is not called, then the garbage collector * will still remove the reference as it is held via a WeakReference. *

      * The cursor enables iteration and list changes to occur in any order without * invalidating the iterator (from one thread). When elements are added to the * list, an event is fired to all active cursors enabling them to adjust to the * change in the list. *

      * When the "current" (i.e., last returned by {@link ListIterator#next} * or {@link ListIterator#previous}) element of the list is removed, * the cursor automatically adjusts to the change (invalidating the * last returned value such that it cannot be removed). *

      * The {@link #listIterator()} method returns the same as this method, and can * be cast to a Cursor if the close method is required. * * @return a new cursor iterator */ public CursorableLinkedList.Cursor cursor() { return cursor(0); } /** * Returns a {@link Cursor} for iterating through the elements of this list * starting from a specified index. *

      * A Cursor is a ListIterator with an additional * close() method. Calling this method immediately discards the * references to the cursor. If it is not called, then the garbage collector * will still remove the reference as it is held via a WeakReference. *

      * The cursor enables iteration and list changes to occur in any order without * invalidating the iterator (from one thread). When elements are added to the * list, an event is fired to all active cursors enabling them to adjust to the * change in the list. *

      * When the "current" (i.e., last returned by {@link ListIterator#next} * or {@link ListIterator#previous}) element of the list is removed, * the cursor automatically adjusts to the change (invalidating the * last returned value such that it cannot be removed). *

      * The {@link #listIterator(int)} method returns the same as this method, and can * be cast to a Cursor if the close method is required. * * @param fromIndex the index to start from * @return a new cursor iterator * @throws IndexOutOfBoundsException if the index is out of range * (index < 0 || index > size()). */ public CursorableLinkedList.Cursor cursor(int fromIndex) { Cursor cursor = new Cursor(this, fromIndex); registerCursor(cursor); return cursor; } //----------------------------------------------------------------------- /** * Updates the node with a new value. * This implementation sets the value on the node. * Subclasses can override this to record the change. * * @param node node to update * @param value new value of the node */ protected void updateNode(Node node, E value) { super.updateNode(node, value); broadcastNodeChanged(node); } /** * Inserts a new node into the list. * * @param nodeToInsert new node to insert * @param insertBeforeNode node to insert before * @throws NullPointerException if either node is null */ protected void addNode(Node nodeToInsert, Node insertBeforeNode) { super.addNode(nodeToInsert, insertBeforeNode); broadcastNodeInserted(nodeToInsert); } /** * Removes the specified node from the list. * * @param node the node to remove * @throws NullPointerException if node is null */ protected void removeNode(Node node) { super.removeNode(node); broadcastNodeRemoved(node); } /** * Removes all nodes by iteration. */ protected void removeAllNodes() { if (size() > 0) { // superclass implementation would break all the iterators Iterator it = iterator(); while (it.hasNext()) { it.next(); it.remove(); } } } //----------------------------------------------------------------------- /** * Registers a cursor to be notified of changes to this list. * * @param cursor the cursor to register */ protected void registerCursor(Cursor cursor) { // We take this opportunity to clean the cursors list // of WeakReference objects to garbage-collected cursors. for (Iterator>> it = cursors.iterator(); it.hasNext();) { WeakReference> ref = it.next(); if (ref.get() == null) { it.remove(); } } cursors.add(new WeakReference>(cursor)); } /** * Deregisters a cursor from the list to be notified of changes. * * @param cursor the cursor to deregister */ protected void unregisterCursor(Cursor cursor) { for (Iterator it = cursors.iterator(); it.hasNext();) { WeakReference ref = (WeakReference) it.next(); Cursor cur = (Cursor) ref.get(); if (cur == null) { // some other unrelated cursor object has been // garbage-collected; let's take the opportunity to // clean up the cursors list anyway.. it.remove(); } else if (cur == cursor) { ref.clear(); it.remove(); break; } } } //----------------------------------------------------------------------- /** * Informs all of my registered cursors that the specified * element was changed. * * @param node the node that was changed */ protected void broadcastNodeChanged(Node node) { Iterator it = cursors.iterator(); while (it.hasNext()) { WeakReference ref = (WeakReference) it.next(); Cursor cursor = (Cursor) ref.get(); if (cursor == null) { it.remove(); // clean up list } else { cursor.nodeChanged(node); } } } /** * Informs all of my registered cursors that the specified * element was just removed from my list. * * @param node the node that was changed */ protected void broadcastNodeRemoved(Node node) { Iterator it = cursors.iterator(); while (it.hasNext()) { WeakReference ref = (WeakReference) it.next(); Cursor cursor = (Cursor) ref.get(); if (cursor == null) { it.remove(); // clean up list } else { cursor.nodeRemoved(node); } } } /** * Informs all of my registered cursors that the specified * element was just added to my list. * * @param node the node that was changed */ protected void broadcastNodeInserted(Node node) { Iterator it = cursors.iterator(); while (it.hasNext()) { WeakReference ref = (WeakReference) it.next(); Cursor cursor = (Cursor) ref.get(); if (cursor == null) { it.remove(); // clean up list } else { cursor.nodeInserted(node); } } } //----------------------------------------------------------------------- /** * Serializes the data held in this object to the stream specified. */ private void writeObject(ObjectOutputStream out) throws IOException { out.defaultWriteObject(); doWriteObject(out); } /** * Deserializes the data held in this object to the stream specified. */ private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); doReadObject(in); } //----------------------------------------------------------------------- /** * An extended ListIterator that allows concurrent changes to * the underlying list. */ public static class Cursor extends AbstractLinkedList.LinkedListIterator { /** * Is the cursor valid (not closed) */ boolean valid = true; /** * Is the next index valid */ boolean nextIndexValid = true; /** * Constructs a new cursor. * * @param index the index to start from */ protected Cursor(CursorableLinkedList parent, int index) { super(parent, index); valid = true; } /** * Adds an object to the list. * The object added here will be the new 'previous' in the iterator. * * @param obj the object to add */ public void add(E obj) { super.add(obj); // add on iterator does not return the added element next = next.next; } /** * Gets the index of the next element to be returned. * * @return the next index */ public int nextIndex() { if (nextIndexValid == false) { if (next == parent.header) { nextIndex = parent.size(); } else { int pos = 0; Node temp = parent.header.next; while (temp != next) { pos++; temp = temp.next; } nextIndex = pos; } nextIndexValid = true; } return nextIndex; } /** * Handle event from the list when a node has changed. * * @param node the node that changed */ protected void nodeChanged(Node node) { // do nothing } /** * Handle event from the list when a node has been removed. * * @param node the node that was removed */ protected void nodeRemoved(Node node) { if (node == next) { next = node.next; } else if (node == current) { current = null; nextIndex--; } else { nextIndexValid = false; } } /** * Handle event from the list when a node has been added. * * @param node the node that was added */ protected void nodeInserted(Node node) { if (node.previous == current) { next = node; } else if (next.previous == node) { next = node; } else { nextIndexValid = false; } } /** * Override superclass modCount check, and replace it with our valid flag. */ protected void checkModCount() { if (!valid) { throw new ConcurrentModificationException("Cursor closed"); } } /** * Mark this cursor as no longer being needed. Any resources * associated with this cursor are immediately released. * In previous versions of this class, it was mandatory to close * all cursor objects to avoid memory leaks. It is no longer * necessary to call this close method; an instance of this class * can now be treated exactly like a normal iterator. */ public void close() { if (valid) { ((CursorableLinkedList) parent).unregisterCursor(this); valid = false; } } } } collections-generic-4.01/src/java/org/apache/commons/collections15/list/AbstractListDecorator.java0000644000175000017500000000560510464140761033544 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.list; import org.apache.commons.collections15.collection.AbstractCollectionDecorator; import java.util.Collection; import java.util.List; import java.util.ListIterator; /** * Decorates another List to provide additional behaviour. *

      * Methods are forwarded directly to the decorated list. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:32 $ * @since Commons Collections 3.0 */ public abstract class AbstractListDecorator extends AbstractCollectionDecorator implements List { /** * Constructor only used in deserialization, do not use otherwise. * * @since Commons Collections 3.1 */ protected AbstractListDecorator() { super(); } /** * Constructor that wraps (not copies). * * @param list the list to decorate, must not be null * @throws IllegalArgumentException if list is null */ protected AbstractListDecorator(List list) { super(list); } /** * Gets the list being decorated. * * @return the decorated list */ protected List getList() { return (List) getCollection(); } //----------------------------------------------------------------------- public void add(int index, E object) { getList().add(index, object); } public boolean addAll(int index, Collection coll) { return getList().addAll(index, coll); } public E get(int index) { return getList().get(index); } public int indexOf(Object object) { return getList().indexOf(object); } public int lastIndexOf(Object object) { return getList().lastIndexOf(object); } public ListIterator listIterator() { return getList().listIterator(); } public ListIterator listIterator(int index) { return getList().listIterator(index); } public E remove(int index) { return getList().remove(index); } public E set(int index, E object) { return getList().set(index, object); } public List subList(int fromIndex, int toIndex) { return getList().subList(fromIndex, toIndex); } } collections-generic-4.01/src/java/org/apache/commons/collections15/list/SetUniqueList.java0000644000175000017500000002425110464140753032057 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.list; import org.apache.commons.collections15.iterators.AbstractIteratorDecorator; import org.apache.commons.collections15.iterators.AbstractListIteratorDecorator; import org.apache.commons.collections15.set.UnmodifiableSet; import java.util.*; /** * Decorates a List to ensure that no duplicates are present * much like a Set. *

      * The List interface makes certain assumptions/requirements. * This implementation breaks these in certain ways, but this is merely the * result of rejecting duplicates. * Each violation is explained in the method, but it should not affect you. *

      * The {@link org.apache.commons.collections15.set.ListOrderedSet ListOrderedSet} * class provides an alternative approach, by wrapping an existing Set and * retaining insertion order in the iterator. *

      * This class is Serializable from Commons Collections 3.1. * * @author Matthew Hawthorne * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:32 $ * @since Commons Collections 3.0 */ public class SetUniqueList extends AbstractSerializableListDecorator { /** * Serialization version */ private static final long serialVersionUID = 7196982186153478694L; /** * Internal Set to maintain uniqueness. */ protected final Set set; /** * Factory method to create a SetList using the supplied list to retain order. *

      * If the list contains duplicates, these are removed (first indexed one kept). * A HashSet is used for the set behaviour. * * @param list the list to decorate, must not be null * @throws IllegalArgumentException if list is null */ public static SetUniqueList decorate(List list) { if (list == null) { throw new IllegalArgumentException("List must not be null"); } if (list.isEmpty()) { return new SetUniqueList(list, new HashSet()); } else { List temp = new ArrayList(list); list.clear(); SetUniqueList sl = new SetUniqueList(list, new HashSet()); sl.addAll(temp); return sl; } } //----------------------------------------------------------------------- /** * Constructor that wraps (not copies) the List and specifies the set to use. *

      * The set and list must both be correctly initialised to the same elements. * * @param set the set to decorate, must not be null * @param list the list to decorate, must not be null * @throws IllegalArgumentException if set or list is null */ protected SetUniqueList(List list, Set set) { super(list); if (set == null) { throw new IllegalArgumentException("Set must not be null"); } this.set = set; } //----------------------------------------------------------------------- /** * Gets an unmodifiable view as a Set. * * @return an unmodifiable set view */ public Set asSet() { return UnmodifiableSet.decorate(set); } //----------------------------------------------------------------------- /** * Adds an element to the list if it is not already present. *

      * (Violation) * The List interface requires that this method returns * true always. However this class may return false * because of the Set behaviour. * * @param object the object to add * @return true if object was added */ public boolean add(E object) { // gets initial size final int sizeBefore = size(); // adds element if unique add(size(), object); // compares sizes to detect if collection changed return (sizeBefore != size()); } /** * Adds an element to a specific index in the list if it is not already present. *

      * (Violation) * The List interface makes the assumption that the element is * always inserted. This may not happen with this implementation. * * @param index the index to insert at * @param object the object to add */ public void add(int index, E object) { // adds element if it is not contained already if (set.contains(object) == false) { super.add(index, object); set.add(object); } } /** * Adds an element to the end of the list if it is not already present. *

      * (Violation) * The List interface makes the assumption that the element is * always inserted. This may not happen with this implementation. * * @param coll the collection to add */ public boolean addAll(Collection coll) { return addAll(size(), coll); } /** * Adds a collection of objects to the end of the list avoiding duplicates. *

      * Only elements that are not already in this list will be added, and * duplicates from the specified collection will be ignored. *

      * (Violation) * The List interface makes the assumption that the elements * are always inserted. This may not happen with this implementation. * * @param index the index to insert at * @param coll the collection to add in iterator order * @return true if this collection changed */ public boolean addAll(int index, Collection coll) { // gets initial size final int sizeBefore = size(); // adds all elements for (final Iterator it = coll.iterator(); it.hasNext();) { add((E) it.next()); } // compares sizes to detect if collection changed return sizeBefore != size(); } //----------------------------------------------------------------------- /** * Sets the value at the specified index avoiding duplicates. *

      * The object is set into the specified index. * Afterwards, any previous duplicate is removed * If the object is not already in the list then a normal set occurs. * If it is present, then the old version is removed and re-added at this index * * @param index the index to insert at * @param object the object to set * @return the previous object */ public E set(int index, E object) { int pos = indexOf(object); E result = super.set(index, object); if (pos == -1 || pos == index) { return result; } return remove(pos); } public boolean remove(Object object) { boolean result = super.remove(object); set.remove(object); return result; } public E remove(int index) { E result = super.remove(index); set.remove(result); return result; } public boolean removeAll(Collection coll) { boolean result = super.removeAll(coll); set.removeAll(coll); return result; } public boolean retainAll(Collection coll) { boolean result = super.retainAll(coll); set.retainAll(coll); return result; } public void clear() { super.clear(); set.clear(); } public boolean contains(Object object) { return set.contains(object); } public boolean containsAll(Collection coll) { return set.containsAll(coll); } public Iterator iterator() { return new SetListIterator(super.iterator(), set); } public ListIterator listIterator() { return new SetListListIterator(super.listIterator(), set); } public ListIterator listIterator(int index) { return new SetListListIterator(super.listIterator(index), set); } public List subList(int fromIndex, int toIndex) { return new SetUniqueList(super.subList(fromIndex, toIndex), set); } //----------------------------------------------------------------------- /** * Inner class iterator. */ static class SetListIterator extends AbstractIteratorDecorator { protected final Set set; protected E last = null; protected SetListIterator(Iterator it, Set set) { super(it); this.set = set; } public E next() { last = super.next(); return last; } public void remove() { super.remove(); set.remove(last); last = null; } } /** * Inner class iterator. */ static class SetListListIterator extends AbstractListIteratorDecorator { protected final Set set; protected E last = null; protected SetListListIterator(ListIterator it, Set set) { super(it); this.set = set; } public E next() { last = super.next(); return last; } public E previous() { last = super.previous(); return last; } public void remove() { super.remove(); set.remove(last); last = null; } public void add(E object) { if (set.contains(object) == false) { super.add(object); set.add(object); } } public void set(E object) { throw new UnsupportedOperationException("ListIterator does not support set"); } } } collections-generic-4.01/src/java/org/apache/commons/collections15/list/TypedList.java0000644000175000017500000000402710464140762031221 0ustar giovannigiovanni// GenericsNote: deprecated and useless /* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.list; import org.apache.commons.collections15.functors.InstanceofPredicate; import java.util.List; /** * Decorates another List to validate that elements * added are of a specific type. *

      * The validation of additions is performed via an instanceof test against * a specified Class. If an object cannot be added to the * collection, an IllegalArgumentException is thrown. * * @author Stephen Colebourne * @author Matt Hall, John Watkinson, Matthew Hawthorne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:32 $ * @since Commons Collections 3.0 * @deprecated Java Generics makes this class obsolete. */ public class TypedList { /** * Factory method to create a typed list. *

      * If there are any elements already in the list being decorated, they * are validated. * * @param list the list to decorate, must not be null * @param type the type to allow into the collection, must not be null * @throws IllegalArgumentException if list or type is null * @throws IllegalArgumentException if the list contains invalid elements */ public static List decorate(List list, Class type) { return new PredicatedList(list, InstanceofPredicate.getInstance(type)); } /** * Restrictive constructor. */ protected TypedList() { } } collections-generic-4.01/src/java/org/apache/commons/collections15/list/TreeList.java0000644000175000017500000007112010464140761031030 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.list; import org.apache.commons.collections15.OrderedIterator; import java.util.*; /** * A List implementation that is optimised for fast insertions and * removals at any index in the list. *

      * This list implementation utilises a tree structure internally to ensure that * all insertions and removals are O(log n). This provides much faster performance * than both an ArrayList and a LinkedList where elements * are inserted and removed repeatedly from anywhere in the list. *

      * The following relative performance statistics are indicative of this class: *

       *              get  add  insert  iterate  remove
       * TreeList       3    5       1       2       1
       * ArrayList      1    1      40       1      40
       * LinkedList  5800    1     350       2     325
       * 
      * ArrayList is a good general purpose list implementation. * It is faster than TreeList for most operations except inserting * and removing in the middle of the list. ArrayList also uses less * memory as TreeList uses one object per entry. *

      * LinkedList is rarely a good choice of implementation. * TreeList is almost always a good replacement for it, although it * does use sligtly more memory. * * @author Matt Hall, John Watkinson, Joerg Schmuecker * @author Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:32 $ * @since Commons Collections 3.1 */ public class TreeList extends AbstractList { // add; toArray; iterator; insert; get; indexOf; remove // TreeList = 1260;7360;3080; 160; 170;3400; 170; // ArrayList = 220;1480;1760; 6870; 50;1540; 7200; // LinkedList = 270;7360;3350;55860;290720;2910;55200; /** * The root node in the AVL tree */ private AVLNode root; /** * The current size of the list */ private int size; //----------------------------------------------------------------------- /** * Constructs a new empty list. */ public TreeList() { super(); } /** * Constructs a new empty list that copies the specified list. * * @param coll the collection to copy * @throws NullPointerException if the collection is null */ public TreeList(Collection coll) { super(); addAll(coll); } //----------------------------------------------------------------------- /** * Gets the element at the specified index. * * @param index the index to retrieve * @return the element at the specified index */ public E get(int index) { checkInterval(index, 0, size() - 1); return root.get(index).getValue(); } /** * Gets the current size of the list. * * @return the current size */ public int size() { return size; } /** * Gets an iterator over the list. * * @return an iterator over the list */ public Iterator iterator() { // override to go 75% faster return listIterator(0); } /** * Gets a ListIterator over the list. * * @return the new iterator */ public ListIterator listIterator() { // override to go 75% faster return listIterator(0); } /** * Gets a ListIterator over the list. * * @param fromIndex the index to start from * @return the new iterator */ public ListIterator listIterator(int fromIndex) { // override to go 75% faster // cannot use EmptyIterator as iterator.add() must work checkInterval(fromIndex, 0, size()); return new TreeListIterator(this, fromIndex); } /** * Searches for the index of an object in the list. * * @return the index of the object, -1 if not found */ public int indexOf(Object object) { // override to go 75% faster if (root == null) { return -1; } return root.indexOf((E) object, root.relativePosition); } /** * Searches for the presence of an object in the list. * * @return true if the object is found */ public boolean contains(Object object) { return (indexOf(object) >= 0); } /** * Converts the list into an array. * * @return the list as an array */ public Object[] toArray() { // override to go 20% faster Object[] array = new Object[size()]; if (root != null) { root.toArray((E[]) array, root.relativePosition); } return array; } //----------------------------------------------------------------------- /** * Adds a new element to the list. * * @param index the index to add before * @param obj the element to add */ public void add(int index, E obj) { modCount++; checkInterval(index, 0, size()); if (root == null) { root = new AVLNode(index, obj, null, null); } else { root = root.insert(index, obj); } size++; } /** * Sets the element at the specified index. * * @param index the index to set * @param obj the object to store at the specified index * @return the previous object at that index * @throws IndexOutOfBoundsException if the index is invalid */ public E set(int index, E obj) { checkInterval(index, 0, size() - 1); AVLNode node = root.get(index); E result = node.value; node.setValue(obj); return result; } /** * Removes the element at the specified index. * * @param index the index to remove * @return the previous object at that index */ public E remove(int index) { modCount++; checkInterval(index, 0, size() - 1); E result = get(index); root = root.remove(index); size--; return result; } /** * Clears the list, removing all entries. */ public void clear() { modCount++; root = null; size = 0; } //----------------------------------------------------------------------- /** * Checks whether the index is valid. * * @param index the index to check * @param startIndex the first allowed index * @param endIndex the last allowed index * @throws IndexOutOfBoundsException if the index is invalid */ private void checkInterval(int index, int startIndex, int endIndex) { if (index < startIndex || index > endIndex) { throw new IndexOutOfBoundsException("Invalid index:" + index + ", size=" + size()); } } //----------------------------------------------------------------------- /** * Implements an AVLNode which keeps the offset updated. *

      * This node contains the real work. * TreeList is just there to implement {@link java.util.List}. * The nodes don't know the index of the object they are holding. They * do know however their position relative to their parent node. * This allows to calculate the index of a node while traversing the tree. *

      * The Faedelung calculation stores a flag for both the left and right child * to indicate if they are a child (false) or a link as in linked list (true). */ static class AVLNode { /** * The left child node or the predecessor if {@link #leftIsPrevious}. */ private AVLNode left; /** * Flag indicating that left reference is not a subtree but the predecessor. */ private boolean leftIsPrevious; /** * The right child node or the successor if {@link #rightIsNext}. */ private AVLNode right; /** * Flag indicating that right reference is not a subtree but the successor. */ private boolean rightIsNext; /** * How many levels of left/right are below this one. */ private int height; /** * The relative position, root holds absolute position. */ private int relativePosition; /** * The stored element. */ private T value; /** * Constructs a new node with a relative position. * * @param relativePosition the relative position of the node * @param obj the value for the ndoe * @param rightFollower the node with the value following this one * @param leftFollower the node with the value leading this one */ private AVLNode(int relativePosition, T obj, AVLNode rightFollower, AVLNode leftFollower) { this.relativePosition = relativePosition; value = obj; rightIsNext = true; leftIsPrevious = true; right = rightFollower; left = leftFollower; } /** * Gets the value. * * @return the value of this node */ T getValue() { return value; } /** * Sets the value. * * @param obj the value to store */ void setValue(T obj) { this.value = obj; } /** * Locate the element with the given index relative to the * offset of the parent of this node. */ AVLNode get(int index) { int indexRelativeToMe = index - relativePosition; if (indexRelativeToMe == 0) { return this; } AVLNode nextNode = ((indexRelativeToMe < 0) ? getLeftSubTree() : getRightSubTree()); if (nextNode == null) { return null; } return nextNode.get(indexRelativeToMe); } /** * Locate the index that contains the specified object. */ int indexOf(T object, int index) { if (getLeftSubTree() != null) { int result = left.indexOf(object, index + left.relativePosition); if (result != -1) { return result; } } if (value == null ? value == object : value.equals(object)) { return index; } if (getRightSubTree() != null) { return right.indexOf(object, index + right.relativePosition); } return -1; } /** * Stores the node and its children into the array specified. * * @param array the array to be filled * @param index the index of this node */ void toArray(T[] array, int index) { array[index] = value; if (getLeftSubTree() != null) { left.toArray(array, index + left.relativePosition); } if (getRightSubTree() != null) { right.toArray(array, index + right.relativePosition); } } /** * Gets the next node in the list after this one. * * @return the next node */ AVLNode next() { if (rightIsNext || right == null) { return right; } return right.min(); } /** * Gets the node in the list before this one. * * @return the previous node */ AVLNode previous() { if (leftIsPrevious || left == null) { return left; } return left.max(); } /** * Inserts a node at the position index. * * @param index is the index of the position relative to the position of * the parent node. * @param obj is the object to be stored in the position. */ AVLNode insert(int index, T obj) { int indexRelativeToMe = index - relativePosition; if (indexRelativeToMe <= 0) { return insertOnLeft(indexRelativeToMe, obj); } else { return insertOnRight(indexRelativeToMe, obj); } } private AVLNode insertOnLeft(int indexRelativeToMe, T obj) { AVLNode ret = this; if (getLeftSubTree() == null) { setLeft(new AVLNode(-1, obj, this, left), null); } else { setLeft(left.insert(indexRelativeToMe, obj), null); } if (relativePosition >= 0) { relativePosition++; } ret = balance(); recalcHeight(); return ret; } private AVLNode insertOnRight(int indexRelativeToMe, T obj) { AVLNode ret = this; if (getRightSubTree() == null) { setRight(new AVLNode(+1, obj, right, this), null); } else { setRight(right.insert(indexRelativeToMe, obj), null); } if (relativePosition < 0) { relativePosition--; } ret = balance(); recalcHeight(); return ret; } //----------------------------------------------------------------------- /** * Gets the left node, returning null if its a faedelung. */ private AVLNode getLeftSubTree() { return (leftIsPrevious ? null : left); } /** * Gets the right node, returning null if its a faedelung. */ private AVLNode getRightSubTree() { return (rightIsNext ? null : right); } /** * Gets the rightmost child of this node. * * @return the rightmost child (greatest index) */ private AVLNode max() { return (getRightSubTree() == null) ? this : right.max(); } /** * Gets the leftmost child of this node. * * @return the leftmost child (smallest index) */ private AVLNode min() { return (getLeftSubTree() == null) ? this : left.min(); } /** * Removes the node at a given position. * * @param index is the index of the element to be removed relative to the position of * the parent node of the current node. */ AVLNode remove(int index) { int indexRelativeToMe = index - relativePosition; if (indexRelativeToMe == 0) { return removeSelf(); } if (indexRelativeToMe > 0) { setRight(right.remove(indexRelativeToMe), right.right); if (relativePosition < 0) { relativePosition++; } } else { setLeft(left.remove(indexRelativeToMe), left.left); if (relativePosition > 0) { relativePosition--; } } recalcHeight(); return balance(); } private AVLNode removeMax() { if (getRightSubTree() == null) { return removeSelf(); } setRight(right.removeMax(), right.right); if (relativePosition < 0) { relativePosition++; } recalcHeight(); return balance(); } private AVLNode removeMin() { if (getLeftSubTree() == null) { return removeSelf(); } setLeft(left.removeMin(), left.left); if (relativePosition > 0) { relativePosition--; } recalcHeight(); return balance(); } private AVLNode removeSelf() { if (getRightSubTree() == null && getLeftSubTree() == null) return null; if (getRightSubTree() == null) { if (relativePosition > 0) { left.relativePosition += relativePosition + (relativePosition > 0 ? 0 : 1); } left.max().setRight(null, right); return left; } if (getLeftSubTree() == null) { right.relativePosition += relativePosition - (relativePosition < 0 ? 0 : 1); right.min().setLeft(null, left); return right; } if (heightRightMinusLeft() > 0) { AVLNode rightMin = right.min(); value = rightMin.value; if (leftIsPrevious) { left = rightMin.left; } right = right.removeMin(); if (relativePosition < 0) { relativePosition++; } } else { AVLNode leftMax = left.max(); value = leftMax.value; if (rightIsNext) { right = leftMax.right; } left = left.removeMax(); if (relativePosition > 0) { relativePosition--; } } recalcHeight(); return this; } //----------------------------------------------------------------------- /** * Balances according to the AVL algorithm. */ private AVLNode balance() { switch (heightRightMinusLeft()) { case 1: case 0: case -1: return this; case -2: if (left.heightRightMinusLeft() > 0) { setLeft(left.rotateLeft(), null); } return rotateRight(); case 2: if (right.heightRightMinusLeft() < 0) { setRight(right.rotateRight(), null); } return rotateLeft(); default : throw new RuntimeException("tree inconsistent!"); } } /** * Gets the relative position. */ private int getOffset(AVLNode node) { if (node == null) { return 0; } return node.relativePosition; } /** * Sets the relative position. */ private int setOffset(AVLNode node, int newOffest) { if (node == null) { return 0; } int oldOffset = getOffset(node); node.relativePosition = newOffest; return oldOffset; } /** * Sets the height by calculation. */ private void recalcHeight() { height = Math.max(getLeftSubTree() == null ? -1 : getLeftSubTree().height, getRightSubTree() == null ? -1 : getRightSubTree().height) + 1; } /** * Returns the height of the node or -1 if the node is null. */ private int getHeight(AVLNode node) { return (node == null ? -1 : node.height); } /** * Returns the height difference right - left */ private int heightRightMinusLeft() { return getHeight(getRightSubTree()) - getHeight(getLeftSubTree()); } private AVLNode rotateLeft() { AVLNode newTop = right; // can't be faedelung! AVLNode movedNode = getRightSubTree().getLeftSubTree(); int newTopPosition = relativePosition + getOffset(newTop); int myNewPosition = -newTop.relativePosition; int movedPosition = getOffset(newTop) + getOffset(movedNode); setRight(movedNode, newTop); newTop.setLeft(this, null); setOffset(newTop, newTopPosition); setOffset(this, myNewPosition); setOffset(movedNode, movedPosition); return newTop; } private AVLNode rotateRight() { AVLNode newTop = left; // can't be faedelung AVLNode movedNode = getLeftSubTree().getRightSubTree(); int newTopPosition = relativePosition + getOffset(newTop); int myNewPosition = -newTop.relativePosition; int movedPosition = getOffset(newTop) + getOffset(movedNode); setLeft(movedNode, newTop); newTop.setRight(this, null); setOffset(newTop, newTopPosition); setOffset(this, myNewPosition); setOffset(movedNode, movedPosition); return newTop; } private void setLeft(AVLNode node, AVLNode previous) { leftIsPrevious = (node == null); left = (leftIsPrevious ? previous : node); recalcHeight(); } private void setRight(AVLNode node, AVLNode next) { rightIsNext = (node == null); right = (rightIsNext ? next : node); recalcHeight(); } // private void checkFaedelung() { // AVLNode maxNode = left.max(); // if (!maxNode.rightIsFaedelung || maxNode.right != this) { // throw new RuntimeException(maxNode + " should right-faedel to " + this); // } // AVLNode minNode = right.min(); // if (!minNode.leftIsFaedelung || minNode.left != this) { // throw new RuntimeException(maxNode + " should left-faedel to " + this); // } // } // // private int checkTreeDepth() { // int hright = (getRightSubTree() == null ? -1 : getRightSubTree().checkTreeDepth()); // // System.out.print("checkTreeDepth"); // // System.out.print(this); // // System.out.print(" left: "); // // System.out.print(_left); // // System.out.print(" right: "); // // System.out.println(_right); // // int hleft = (left == null ? -1 : left.checkTreeDepth()); // if (height != Math.max(hright, hleft) + 1) { // throw new RuntimeException( // "height should be max" + hleft + "," + hright + " but is " + height); // } // return height; // } // // private int checkLeftSubNode() { // if (getLeftSubTree() == null) { // return 0; // } // int count = 1 + left.checkRightSubNode(); // if (left.relativePosition != -count) { // throw new RuntimeException(); // } // return count + left.checkLeftSubNode(); // } // // private int checkRightSubNode() { // AVLNode right = getRightSubTree(); // if (right == null) { // return 0; // } // int count = 1; // count += right.checkLeftSubNode(); // if (right.relativePosition != count) { // throw new RuntimeException(); // } // return count + right.checkRightSubNode(); // } /** * Used for debugging. */ public String toString() { return "AVLNode(" + relativePosition + "," + (left != null) + "," + value + "," + (getRightSubTree() != null) + ", faedelung " + rightIsNext + " )"; } } /** * A list iterator over the linked list. */ static class TreeListIterator implements ListIterator, OrderedIterator { /** * The parent list */ protected final TreeList parent; /** * The node that will be returned by {@link #next()}. If this is equal * to {@link AbstractLinkedList#header} then there are no more values to return. */ protected AVLNode next; /** * The index of {@link #next}. */ protected int nextIndex; /** * The last node that was returned by {@link #next()} or {@link * #previous()}. Set to null if {@link #next()} or {@link * #previous()} haven't been called, or if the node has been removed * with {@link #remove()} or a new node added with {@link #add(Object)}. * Should be accessed through {@link #getLastNodeReturned()} to enforce * this behaviour. */ protected AVLNode current; /** * The index of {@link #current}. */ protected int currentIndex; /** * The modification count that the list is expected to have. If the list * doesn't have this count, then a * {@link java.util.ConcurrentModificationException} may be thrown by * the operations. */ protected int expectedModCount; /** * Create a ListIterator for a list. * * @param parent the parent list * @param fromIndex the index to start at */ protected TreeListIterator(TreeList parent, int fromIndex) throws IndexOutOfBoundsException { super(); this.parent = parent; this.expectedModCount = parent.modCount; this.next = (parent.root == null ? null : parent.root.get(fromIndex)); this.nextIndex = fromIndex; } /** * Checks the modification count of the list is the value that this * object expects. * * @throws ConcurrentModificationException * If the list's modification * count isn't the value that was expected. */ protected void checkModCount() { if (parent.modCount != expectedModCount) { throw new ConcurrentModificationException(); } } public boolean hasNext() { return (nextIndex < parent.size()); } public E next() { checkModCount(); if (!hasNext()) { throw new NoSuchElementException("No element at index " + nextIndex + "."); } if (next == null) { next = parent.root.get(nextIndex); } E value = next.getValue(); current = next; currentIndex = nextIndex++; next = next.next(); return value; } public boolean hasPrevious() { return (nextIndex > 0); } public E previous() { checkModCount(); if (!hasPrevious()) { throw new NoSuchElementException("Already at start of list."); } if (next == null) { next = parent.root.get(nextIndex - 1); } else { next = next.previous(); } E value = next.getValue(); current = next; currentIndex = --nextIndex; return value; } public int nextIndex() { return nextIndex; } public int previousIndex() { return nextIndex() - 1; } public void remove() { checkModCount(); if (current == null) { throw new IllegalStateException(); } parent.remove(currentIndex); current = null; currentIndex = -1; nextIndex--; expectedModCount++; } public void set(E obj) { checkModCount(); if (current == null) { throw new IllegalStateException(); } current.setValue(obj); } public void add(E obj) { checkModCount(); parent.add(nextIndex, obj); current = null; currentIndex = -1; nextIndex++; expectedModCount++; } } } collections-generic-4.01/src/java/org/apache/commons/collections15/list/PredicatedList.java0000644000175000017500000001224410464140756032203 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.list; import org.apache.commons.collections15.Predicate; import org.apache.commons.collections15.collection.PredicatedCollection; import org.apache.commons.collections15.iterators.AbstractListIteratorDecorator; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.ListIterator; /** * Decorates another List to validate that all additions * match a specified predicate. *

      * This list exists to provide validation for the decorated list. * It is normally created to decorate an empty list. * If an object cannot be added to the list, an IllegalArgumentException is thrown. *

      * One usage would be to ensure that no null entries are added to the list. *

      List list = PredicatedList.decorate(new ArrayList(), NotNullPredicate.INSTANCE);
      *

      * This class is Serializable from Commons Collections 3.1. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @author Paul Jack * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:32 $ * @since Commons Collections 3.0 */ public class PredicatedList extends PredicatedCollection implements List { /** * Serialization version */ private static final long serialVersionUID = -5722039223898659102L; /** * Factory method to create a predicated (validating) list. *

      * If there are any elements already in the list being decorated, they * are validated. * * @param list the list to decorate, must not be null * @param predicate the predicate to use for validation, must not be null * @throws IllegalArgumentException if list or predicate is null * @throws IllegalArgumentException if the list contains invalid elements */ public static List decorate(List list, Predicate predicate) { return new PredicatedList(list, predicate); } //----------------------------------------------------------------------- /** * Constructor that wraps (not copies). *

      * If there are any elements already in the list being decorated, they * are validated. * * @param list the list to decorate, must not be null * @param predicate the predicate to use for validation, must not be null * @throws IllegalArgumentException if list or predicate is null * @throws IllegalArgumentException if the list contains invalid elements */ protected PredicatedList(List list, Predicate predicate) { super(list, predicate); } /** * Gets the list being decorated. * * @return the decorated list */ protected List getList() { return (List) getCollection(); } //----------------------------------------------------------------------- public E get(int index) { return getList().get(index); } public int indexOf(Object object) { return getList().indexOf(object); } public int lastIndexOf(Object object) { return getList().lastIndexOf(object); } public E remove(int index) { return getList().remove(index); } //----------------------------------------------------------------------- public void add(int index, E object) { validate(object); getList().add(index, object); } public boolean addAll(int index, Collection coll) { for (Iterator it = coll.iterator(); it.hasNext();) { validate(it.next()); } return getList().addAll(index, coll); } public ListIterator listIterator() { return listIterator(0); } public ListIterator listIterator(int i) { return new PredicatedListIterator(getList().listIterator(i)); } public E set(int index, E object) { validate(object); return getList().set(index, object); } public List subList(int fromIndex, int toIndex) { List sub = getList().subList(fromIndex, toIndex); return new PredicatedList(sub, predicate); } /** * Inner class Iterator for the PredicatedList */ protected class PredicatedListIterator extends AbstractListIteratorDecorator { protected PredicatedListIterator(ListIterator iterator) { super(iterator); } public void add(E object) { validate(object); iterator.add(object); } public void set(E object) { validate(object); iterator.set(object); } } } ././@LongLink0000000000000000000000000000015700000000000011570 Lustar rootrootcollections-generic-4.01/src/java/org/apache/commons/collections15/list/AbstractSerializableListDecorator.javacollections-generic-4.01/src/java/org/apache/commons/collections15/list/AbstractSerializableListDeco0000644000175000017500000000411310464140756034100 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.list; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.Collection; import java.util.List; /** * Serializable subclass of AbstractListDecorator. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @since Commons Collections 3.1 */ public abstract class AbstractSerializableListDecorator extends AbstractListDecorator implements Serializable { /** * Serialization version */ private static final long serialVersionUID = 2684959196747496299L; /** * Constructor. */ protected AbstractSerializableListDecorator(List list) { super(list); } //----------------------------------------------------------------------- /** * Write the list out using a custom routine. * * @param out the output stream * @throws IOException */ private void writeObject(ObjectOutputStream out) throws IOException { out.defaultWriteObject(); out.writeObject(collection); } /** * Read the list in using a custom routine. * * @param in the input stream * @throws IOException * @throws ClassNotFoundException */ private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); collection = (Collection) in.readObject(); } } collections-generic-4.01/src/java/org/apache/commons/collections15/list/UnmodifiableList.java0000644000175000017500000000763610464140756032546 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.list; import org.apache.commons.collections15.Unmodifiable; import org.apache.commons.collections15.iterators.UnmodifiableIterator; import org.apache.commons.collections15.iterators.UnmodifiableListIterator; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.ListIterator; /** * Decorates another List to ensure it can't be altered. *

      * This class is Serializable from Commons Collections 3.1. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:32 $ * @since Commons Collections 3.0 */ public final class UnmodifiableList extends AbstractSerializableListDecorator implements Unmodifiable { /** * Serialization version */ private static final long serialVersionUID = 6595182819922443652L; /** * Factory method to create an unmodifiable list. * * @param list the list to decorate, must not be null * @throws IllegalArgumentException if list is null */ public static List decorate(List list) { if (list instanceof Unmodifiable) { return list; } return new UnmodifiableList(list); } //----------------------------------------------------------------------- /** * Constructor that wraps (not copies). * * @param list the list to decorate, must not be null * @throws IllegalArgumentException if list is null */ private UnmodifiableList(List list) { super(list); } //----------------------------------------------------------------------- public Iterator iterator() { return UnmodifiableIterator.decorate(getCollection().iterator()); } public boolean add(E object) { throw new UnsupportedOperationException(); } public boolean addAll(Collection coll) { throw new UnsupportedOperationException(); } public void clear() { throw new UnsupportedOperationException(); } public boolean remove(Object object) { throw new UnsupportedOperationException(); } public boolean removeAll(Collection coll) { throw new UnsupportedOperationException(); } public boolean retainAll(Collection coll) { throw new UnsupportedOperationException(); } //----------------------------------------------------------------------- public ListIterator listIterator() { return UnmodifiableListIterator.decorate(getList().listIterator()); } public ListIterator listIterator(int index) { return UnmodifiableListIterator.decorate(getList().listIterator(index)); } public void add(int index, E object) { throw new UnsupportedOperationException(); } public boolean addAll(int index, Collection coll) { throw new UnsupportedOperationException(); } public E remove(int index) { throw new UnsupportedOperationException(); } public E set(int index, E object) { throw new UnsupportedOperationException(); } public List subList(int fromIndex, int toIndex) { List sub = getList().subList(fromIndex, toIndex); return new UnmodifiableList(sub); } } collections-generic-4.01/src/java/org/apache/commons/collections15/list/SynchronizedList.java0000644000175000017500000001126710464140762032617 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.list; import org.apache.commons.collections15.collection.SynchronizedCollection; import java.util.Collection; import java.util.List; import java.util.ListIterator; /** * Decorates another List to synchronize its behaviour * for a multi-threaded environment. *

      * Methods are synchronized, then forwarded to the decorated list. *

      * This class is Serializable from Commons Collections 3.1. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:32 $ * @since Commons Collections 3.0 */ public class SynchronizedList extends SynchronizedCollection implements List { /** * Serialization version */ private static final long serialVersionUID = -1403835447328619437L; /** * Factory method to create a synchronized list. * * @param list the list to decorate, must not be null * @throws IllegalArgumentException if list is null */ public static List decorate(List list) { return new SynchronizedList(list); } //----------------------------------------------------------------------- /** * Constructor that wraps (not copies). * * @param list the list to decorate, must not be null * @throws IllegalArgumentException if list is null */ protected SynchronizedList(List list) { super(list); } /** * Constructor that wraps (not copies). * * @param list the list to decorate, must not be null * @param lock the lock to use, must not be null * @throws IllegalArgumentException if list is null */ protected SynchronizedList(List list, Object lock) { super(list, lock); } /** * Gets the decorated list. * * @return the decorated list */ protected List getList() { return (List) collection; } //----------------------------------------------------------------------- public void add(int index, E object) { synchronized (lock) { getList().add(index, object); } } public boolean addAll(int index, Collection coll) { synchronized (lock) { return getList().addAll(index, coll); } } public E get(int index) { synchronized (lock) { return getList().get(index); } } public int indexOf(Object object) { synchronized (lock) { return getList().indexOf(object); } } public int lastIndexOf(Object object) { synchronized (lock) { return getList().lastIndexOf(object); } } /** * Iterators must be manually synchronized. *

           * synchronized (coll) {
           *   ListIterator it = coll.listIterator();
           *   // do stuff with iterator
           * }
           *
           * @return an iterator that must be manually synchronized on the collection
           */
          public ListIterator listIterator() {
              return getList().listIterator();
          }
      
          /**
           * Iterators must be manually synchronized.
           * 
           * synchronized (coll) {
           *   ListIterator it = coll.listIterator(3);
           *   // do stuff with iterator
           * }
           *
           * @return an iterator that must be manually synchronized on the collection
           */
          public ListIterator listIterator(int index) {
              return getList().listIterator(index);
          }
      
          public E remove(int index) {
              synchronized (lock) {
                  return getList().remove(index);
              }
          }
      
          public E set(int index, E object) {
              synchronized (lock) {
                  return getList().set(index, object);
              }
          }
      
          public List subList(int fromIndex, int toIndex) {
              synchronized (lock) {
                  List list = getList().subList(fromIndex, toIndex);
                  // the lock is passed into the constructor here to ensure that the sublist is
                  // synchronized on the same lock as the parent list
                  return new SynchronizedList(list, lock);
              }
          }
      
      }
      collections-generic-4.01/src/java/org/apache/commons/collections15/list/NodeCachingLinkedList.java0000644000175000017500000001720710464140764033433 0ustar  giovannigiovanni// GenericsNote: Converted.
      /*
       *  Copyright 2001-2004 The Apache Software Foundation
       *
       *  Licensed under the Apache License, Version 2.0 (the "License");
       *  you may not use this file except in compliance with the License.
       *  You may obtain a copy of the License at
       *
       *      http://www.apache.org/licenses/LICENSE-2.0
       *
       *  Unless required by applicable law or agreed to in writing, software
       *  distributed under the License is distributed on an "AS IS" BASIS,
       *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
       *  See the License for the specific language governing permissions and
       *  limitations under the License.
       */
      package org.apache.commons.collections15.list;
      
      import java.io.IOException;
      import java.io.ObjectInputStream;
      import java.io.ObjectOutputStream;
      import java.io.Serializable;
      import java.util.Collection;
      
      /**
       * A List implementation that stores a cache of internal Node objects
       * in an effort to reduce wasteful object creation.
       * 

      * A linked list creates one Node for each item of data added. This can result in * a lot of object creation and garbage collection. This implementation seeks to * avoid that by maintaining a store of cached nodes. *

      * This implementation is suitable for long-lived lists where both add and remove * are used. Short-lived lists, or lists which only grow will have worse performance * using this class. *

      * Note that this implementation is not synchronized. * * @author Matt Hall, John Watkinson, Jeff Varszegi * @author Rich Dougherty * @author Phil Steitz * @author Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:32 $ * @since Commons Collections 3.0 */ public class NodeCachingLinkedList extends AbstractLinkedList implements Serializable { /** * Serialization version */ static final long serialVersionUID = 6897789178562232073L; /** * The default value for {@link #maximumCacheSize}. */ protected static final int DEFAULT_MAXIMUM_CACHE_SIZE = 20; /** * The first cached node, or null if no nodes are cached. * Cached nodes are stored in a singly-linked list with * next pointing to the next element. */ protected transient Node firstCachedNode; /** * The size of the cache. */ protected transient int cacheSize; /** * The maximum size of the cache. */ protected int maximumCacheSize; //----------------------------------------------------------------------- /** * Constructor that creates. */ public NodeCachingLinkedList() { this(DEFAULT_MAXIMUM_CACHE_SIZE); } /** * Constructor that copies the specified collection * * @param coll the collection to copy */ public NodeCachingLinkedList(Collection coll) { super(coll); this.maximumCacheSize = DEFAULT_MAXIMUM_CACHE_SIZE; } /** * Constructor that species the maximum cache size. * * @param maximumCacheSize the maximum cache size */ public NodeCachingLinkedList(int maximumCacheSize) { super(); this.maximumCacheSize = maximumCacheSize; init(); // must call init() as use super(); } //----------------------------------------------------------------------- /** * Gets the maximum size of the cache. * * @return the maximum cache size */ protected int getMaximumCacheSize() { return maximumCacheSize; } /** * Sets the maximum size of the cache. * * @param maximumCacheSize the new maximum cache size */ protected void setMaximumCacheSize(int maximumCacheSize) { this.maximumCacheSize = maximumCacheSize; shrinkCacheToMaximumSize(); } /** * Reduce the size of the cache to the maximum, if necessary. */ protected void shrinkCacheToMaximumSize() { // Rich Dougherty: This could be more efficient. while (cacheSize > maximumCacheSize) { getNodeFromCache(); } } /** * Gets a node from the cache. If a node is returned, then the value of * {@link #cacheSize} is decreased accordingly. The node that is returned * will have null values for next, previous and element. * * @return a node, or null if there are no nodes in the cache. */ protected Node getNodeFromCache() { if (cacheSize == 0) { return null; } Node cachedNode = firstCachedNode; firstCachedNode = cachedNode.next; cachedNode.next = null; // This should be changed anyway, but defensively // set it to null. cacheSize--; return cachedNode; } /** * Checks whether the cache is full. * * @return true if the cache is full */ protected boolean isCacheFull() { return cacheSize >= maximumCacheSize; } /** * Adds a node to the cache, if the cache isn't full. * The node's contents are cleared to so they can be garbage collected. * * @param node the node to add to the cache */ protected void addNodeToCache(Node node) { if (isCacheFull()) { // don't cache the node. return; } // clear the node's contents and add it to the cache. Node nextCachedNode = firstCachedNode; node.previous = null; node.next = nextCachedNode; node.setValue(null); firstCachedNode = node; cacheSize++; } //----------------------------------------------------------------------- /** * Creates a new node, either by reusing one from the cache or creating * a new one. * * @param value value of the new node * @return the newly created node */ protected Node createNode(E value) { Node cachedNode = getNodeFromCache(); if (cachedNode == null) { return super.createNode(value); } else { cachedNode.setValue(value); return cachedNode; } } /** * Removes the node from the list, storing it in the cache for reuse * if the cache is not yet full. * * @param node the node to remove */ protected void removeNode(Node node) { super.removeNode(node); addNodeToCache(node); } /** * Removes all the nodes from the list, storing as many as required in the * cache for reuse. */ protected void removeAllNodes() { // Add the removed nodes to the cache, then remove the rest. // We can add them to the cache before removing them, since // {@link AbstractLinkedList.removeAllNodes()} removes the // nodes by removing references directly from {@link #header}. int numberOfNodesToCache = Math.min(size, maximumCacheSize - cacheSize); Node node = header.next; for (int currentIndex = 0; currentIndex < numberOfNodesToCache; currentIndex++) { Node oldNode = node; node = node.next; addNodeToCache(oldNode); } super.removeAllNodes(); } //----------------------------------------------------------------------- /** * Serializes the data held in this object to the stream specified. */ private void writeObject(ObjectOutputStream out) throws IOException { out.defaultWriteObject(); doWriteObject(out); } /** * Deserializes the data held in this object to the stream specified. */ private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); doReadObject(in); } } collections-generic-4.01/src/java/org/apache/commons/collections15/list/TransformedList.java0000644000175000017500000001301710464140754032420 0ustar giovannigiovanni// GenericsNote: Converted, but unfortunately very little type-safety could be achieved without breaking List and ListIterator interfaces. /* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.list; import org.apache.commons.collections15.Transformer; import org.apache.commons.collections15.collection.TransformedCollection; import org.apache.commons.collections15.iterators.AbstractListIteratorDecorator; import java.util.Collection; import java.util.List; import java.util.ListIterator; /** * Decorates another List to transform objects that are added. *

      * The add and set methods are affected by this class. * Thus objects must be removed or searched for using their transformed form. * For example, if the transformation converts Strings to Integers, you must * use the Integer form to remove objects. *

      * This class is Serializable from Commons Collections 3.1. *

      * Note: This class cannot support generics without breaking the Collection contract. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:32 $ * @since Commons Collections 3.0 */ public class TransformedList extends TransformedCollection implements List { /** * Serialization version */ private static final long serialVersionUID = 1077193035000013141L; /** * Factory method to create a transforming list. *

      * If there are any elements already in the list being decorated, they * are NOT transformed. * * @param list the list to decorate, must not be null * @param transformer the transformer to use for conversion, must not be null * @throws IllegalArgumentException if list or transformer is null */ public static List decorate(List list, Transformer transformer) { return new TransformedList(list, transformer); } //----------------------------------------------------------------------- /** * Constructor that wraps (not copies). *

      * If there are any elements already in the list being decorated, they * are NOT transformed. * * @param list the list to decorate, must not be null * @param transformer the transformer to use for conversion, must not be null * @throws IllegalArgumentException if list or transformer is null */ protected TransformedList(List list, Transformer transformer) { super(list, transformer); } /** * Gets the decorated list. * * @return the decorated list */ protected List getList() { return (List) collection; } //----------------------------------------------------------------------- public O get(int index) { return getList().get(index); } public int indexOf(Object object) { return getList().indexOf(object); } public int lastIndexOf(Object object) { return getList().lastIndexOf(object); } public Object remove(int index) { return getList().remove(index); } //----------------------------------------------------------------------- public void add(int index, Object object) { O transformed = transform((I) object); getList().add(index, transformed); } /** * Type-safe version of {@link #add(int, Object)} (but breaks List interface). */ public void addTyped(int index, I object) { add(index, object); } public boolean addAll(int index, Collection coll) { Collection transformed = transform((Collection) coll); return getList().addAll(index, transformed); } public ListIterator listIterator() { return listIterator(0); } public ListIterator listIterator(int i) { return new TransformedListIterator(getList().listIterator(i)); } public O set(int index, Object object) { O transformed = transform((I) object); return getList().set(index, transformed); } /** * Type-safe version of {@link #set(int, Object)} (but breaks List interface). */ public O setTyped(int index, I object) { return set(index, object); } public List subList(int fromIndex, int toIndex) { List sub = getList().subList(fromIndex, toIndex); return new TransformedList(sub, transformer); } /** * Inner class Iterator for the TransformedList */ protected class TransformedListIterator extends AbstractListIteratorDecorator { protected TransformedListIterator(ListIterator iterator) { super(iterator); } public void add(Object object) { O transformed = transform((I) object); iterator.add(transformed); } public void set(Object object) { O transformed = transform((I) object); iterator.set(transformed); } } } collections-generic-4.01/src/java/org/apache/commons/collections15/list/AbstractLinkedList.java0000644000175000017500000007464110464140765033042 0ustar giovannigiovanni// GenericsNote: Converted with possible improvements noted. /* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.list; import org.apache.commons.collections15.OrderedIterator; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.lang.reflect.Array; import java.util.*; /** * An abstract implementation of a linked list which provides numerous points for * subclasses to override. *

      * Overridable methods are provided to change the storage node and to change how * nodes are added to and removed. Hopefully, all you need for unusual subclasses * is here. * * @author Rich Dougherty * @author Phil Steitz * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:32 $ * @since Commons Collections 3.0 */ public abstract class AbstractLinkedList implements List { /* * Implementation notes: * - a standard circular doubly-linked list * - a marker node is stored to mark the start and the end of the list * - node creation and removal always occurs through createNode() and * removeNode(). * - a modification count is kept, with the same semantics as * {@link java.util.LinkedList}. * - respects {@link AbstractList#modCount} */ /** * A {@link Node} which indicates the start and end of the list and does not * hold a value. The value of next is the first item in the * list. The value of of previous is the last item in the list. */ protected transient Node header; /** * The size of the list */ protected transient int size; /** * Modification count for iterators */ protected transient int modCount; /** * Constructor that does nothing intended for deserialization. *

      * If this constructor is used by a serializable subclass then the init() * method must be called. */ protected AbstractLinkedList() { super(); } /** * Constructs a list copying data from the specified collection. * * @param coll the collection to copy */ protected AbstractLinkedList(Collection coll) { super(); init(); addAll(coll); } /** * The equivalent of a default constructor, broken out so it can be called * by any constructor and by readObject. * Subclasses which override this method should make sure they call super, * so the list is initialised properly. */ protected void init() { header = createHeaderNode(); } //----------------------------------------------------------------------- public int size() { return size; } public boolean isEmpty() { return (size() == 0); } public E get(int index) { Node node = getNode(index, false); return node.getValue(); } //----------------------------------------------------------------------- public Iterator iterator() { return listIterator(); } public ListIterator listIterator() { return new LinkedListIterator(this, 0); } public ListIterator listIterator(int fromIndex) { return new LinkedListIterator(this, fromIndex); } //----------------------------------------------------------------------- public int indexOf(Object value) { int i = 0; for (Node node = header.next; node != header; node = node.next) { if (isEqualValue(node.getValue(), (E) value)) { return i; } i++; } return -1; } public int lastIndexOf(Object value) { int i = size - 1; for (Node node = header.previous; node != header; node = node.previous) { if (isEqualValue(node.getValue(), (E) value)) { return i; } i--; } return -1; } public boolean contains(Object value) { return indexOf(value) != -1; } public boolean containsAll(Collection coll) { Iterator it = coll.iterator(); while (it.hasNext()) { if (contains(it.next()) == false) { return false; } } return true; } //----------------------------------------------------------------------- public Object[] toArray() { return toArray(new Object[size]); } public T[] toArray(T[] array) { // Extend the array if needed if (array.length < size) { Class componentType = array.getClass().getComponentType(); array = (T[]) Array.newInstance(componentType, size); } // Copy the values into the array int i = 0; for (Node node = header.next; node != header; node = node.next, i++) { // Can do no better than cast through Object here. array[i] = (T) (Object) node.getValue(); } // Set the value after the last value to null if (array.length > size) { array[size] = null; } return array; } /** * Gets a sublist of the main list. * * @param fromIndexInclusive the index to start from * @param toIndexExclusive the index to end at * @return the new sublist */ public List subList(int fromIndexInclusive, int toIndexExclusive) { return new LinkedSubList(this, fromIndexInclusive, toIndexExclusive); } //----------------------------------------------------------------------- public boolean add(E value) { addLast(value); return true; } public void add(int index, E value) { Node node = getNode(index, true); addNodeBefore(node, value); } public boolean addAll(Collection coll) { return addAll(size, coll); } public boolean addAll(int index, Collection coll) { Node node = getNode(index, true); for (Iterator itr = coll.iterator(); itr.hasNext();) { Object value = itr.next(); addNodeBefore(node, (E) value); } return true; } //----------------------------------------------------------------------- public E remove(int index) { Node node = getNode(index, false); E oldValue = node.getValue(); removeNode(node); return oldValue; } public boolean remove(Object value) { for (Node node = header.next; node != header; node = node.next) { if (isEqualValue(node.getValue(), (E) value)) { removeNode(node); return true; } } return false; } public boolean removeAll(Collection coll) { boolean modified = false; Iterator it = iterator(); while (it.hasNext()) { if (coll.contains(it.next())) { it.remove(); modified = true; } } return modified; } //----------------------------------------------------------------------- public boolean retainAll(Collection coll) { boolean modified = false; Iterator it = iterator(); while (it.hasNext()) { if (coll.contains(it.next()) == false) { it.remove(); modified = true; } } return modified; } public E set(int index, E value) { Node node = getNode(index, false); E oldValue = node.getValue(); updateNode(node, value); return oldValue; } public void clear() { removeAllNodes(); } //----------------------------------------------------------------------- public E getFirst() { Node node = header.next; if (node == header) { throw new NoSuchElementException(); } return node.getValue(); } public E getLast() { Node node = header.previous; if (node == header) { throw new NoSuchElementException(); } return node.getValue(); } public boolean addFirst(E o) { addNodeAfter(header, o); return true; } public boolean addLast(E o) { addNodeBefore(header, o); return true; } public E removeFirst() { Node node = header.next; if (node == header) { throw new NoSuchElementException(); } E oldValue = node.getValue(); removeNode(node); return oldValue; } public E removeLast() { Node node = header.previous; if (node == header) { throw new NoSuchElementException(); } E oldValue = node.getValue(); removeNode(node); return oldValue; } //----------------------------------------------------------------------- public boolean equals(Object obj) { if (obj == this) { return true; } if (obj instanceof List == false) { return false; } List other = (List) obj; if (other.size() != size()) { return false; } ListIterator it1 = listIterator(); ListIterator it2 = other.listIterator(); while (it1.hasNext() && it2.hasNext()) { Object o1 = it1.next(); Object o2 = it2.next(); if (!(o1 == null ? o2 == null : o1.equals(o2))) return false; } return !(it1.hasNext() || it2.hasNext()); } public int hashCode() { int hashCode = 1; Iterator it = iterator(); while (it.hasNext()) { Object obj = it.next(); hashCode = 31 * hashCode + (obj == null ? 0 : obj.hashCode()); } return hashCode; } public String toString() { if (size() == 0) { return "[]"; } StringBuffer buf = new StringBuffer(16 * size()); buf.append("["); Iterator it = iterator(); boolean hasNext = it.hasNext(); while (hasNext) { Object value = it.next(); buf.append(value == this ? "(this Collection)" : value); hasNext = it.hasNext(); if (hasNext) { buf.append(", "); } } buf.append("]"); return buf.toString(); } //----------------------------------------------------------------------- /** * Compares two values for equals. * This implementation uses the equals method. * Subclasses can override this to match differently. * * @param value1 the first value to compare, may be null * @param value2 the second value to compare, may be null * @return true if equal */ protected boolean isEqualValue(E value1, E value2) { return (value1 == value2 || (value1 == null ? false : value1.equals(value2))); } /** * Updates the node with a new value. * This implementation sets the value on the node. * Subclasses can override this to record the change. * * @param node node to update * @param value new value of the node */ protected void updateNode(Node node, E value) { node.setValue(value); } /** * Creates a new node with previous, next and element all set to null. * This implementation creates a new empty Node. * Subclasses can override this to create a different class. * * @return newly created node */ protected Node createHeaderNode() { return new Node(); } /** * Creates a new node with the specified properties. * This implementation creates a new Node with data. * Subclasses can override this to create a different class. * * @param value value of the new node */ protected Node createNode(E value) { return new Node(value); } /** * Creates a new node with the specified object as its * value and inserts it before node. *

      * This implementation uses {@link #createNode(Object)} and * {@link #addNode(AbstractLinkedList.Node,AbstractLinkedList.Node)}. * * @param node node to insert before * @param value value of the newly added node * @throws NullPointerException if node is null */ protected void addNodeBefore(Node node, E value) { Node newNode = createNode(value); addNode(newNode, node); } /** * Creates a new node with the specified object as its * value and inserts it after node. *

      * This implementation uses {@link #createNode(Object)} and * {@link #addNode(AbstractLinkedList.Node,AbstractLinkedList.Node)}. * * @param node node to insert after * @param value value of the newly added node * @throws NullPointerException if node is null */ protected void addNodeAfter(Node node, E value) { Node newNode = createNode(value); addNode(newNode, node.next); } /** * Inserts a new node into the list. * * @param nodeToInsert new node to insert * @param insertBeforeNode node to insert before * @throws NullPointerException if either node is null */ protected void addNode(Node nodeToInsert, Node insertBeforeNode) { nodeToInsert.next = insertBeforeNode; nodeToInsert.previous = insertBeforeNode.previous; insertBeforeNode.previous.next = nodeToInsert; insertBeforeNode.previous = nodeToInsert; size++; modCount++; } /** * Removes the specified node from the list. * * @param node the node to remove * @throws NullPointerException if node is null */ protected void removeNode(Node node) { node.previous.next = node.next; node.next.previous = node.previous; size--; modCount++; } /** * Removes all nodes by resetting the circular list marker. */ protected void removeAllNodes() { header.next = header; header.previous = header; size = 0; modCount++; } /** * Gets the node at a particular index. * * @param index the index, starting from 0 * @param endMarkerAllowed whether or not the end marker can be returned if * startIndex is set to the list's size * @throws IndexOutOfBoundsException if the index is less than 0; equal to * the size of the list and endMakerAllowed is false; or greater than the * size of the list */ protected Node getNode(int index, boolean endMarkerAllowed) throws IndexOutOfBoundsException { // Check the index is within the bounds if (index < 0) { throw new IndexOutOfBoundsException("Couldn't get the node: " + "index (" + index + ") less than zero."); } if (!endMarkerAllowed && index == size) { throw new IndexOutOfBoundsException("Couldn't get the node: " + "index (" + index + ") is the size of the list."); } if (index > size) { throw new IndexOutOfBoundsException("Couldn't get the node: " + "index (" + index + ") greater than the size of the " + "list (" + size + ")."); } // Search the list and get the node Node node; if (index < (size / 2)) { // Search forwards node = header.next; for (int currentIndex = 0; currentIndex < index; currentIndex++) { node = node.next; } } else { // Search backwards node = header; for (int currentIndex = size; currentIndex > index; currentIndex--) { node = node.previous; } } return node; } //----------------------------------------------------------------------- /** * Creates an iterator for the sublist. * * @param subList the sublist to get an iterator for */ protected Iterator createSubListIterator(LinkedSubList subList) { return createSubListListIterator(subList, 0); } /** * Creates a list iterator for the sublist. * * @param subList the sublist to get an iterator for * @param fromIndex the index to start from, relative to the sublist */ protected ListIterator createSubListListIterator(LinkedSubList subList, int fromIndex) { return new LinkedSubListIterator(subList, fromIndex); } //----------------------------------------------------------------------- /** * Serializes the data held in this object to the stream specified. *

      * The first serializable subclass must call this method from * writeObject. */ protected void doWriteObject(ObjectOutputStream outputStream) throws IOException { // Write the size so we know how many nodes to read back outputStream.writeInt(size()); for (Iterator itr = iterator(); itr.hasNext();) { outputStream.writeObject(itr.next()); } } /** * Deserializes the data held in this object to the stream specified. *

      * The first serializable subclass must call this method from * readObject. */ protected void doReadObject(ObjectInputStream inputStream) throws IOException, ClassNotFoundException { init(); int size = inputStream.readInt(); for (int i = 0; i < size; i++) { add((E) inputStream.readObject()); } } //----------------------------------------------------------------------- /** * A node within the linked list. *

      * From Commons Collections 3.1, all access to the value property * is via the methods on this class. */ protected static class Node { /** * A pointer to the node before this node */ protected Node previous; /** * A pointer to the node after this node */ protected Node next; /** * The object contained within this node */ protected T value; /** * Constructs a new header node. */ protected Node() { super(); previous = this; next = this; } /** * Constructs a new node. * * @param value the value to store */ protected Node(T value) { super(); this.value = value; } /** * Constructs a new node. * * @param previous the previous node in the list * @param next the next node in the list * @param value the value to store */ protected Node(Node previous, Node next, T value) { super(); this.previous = previous; this.next = next; this.value = value; } /** * Gets the value of the node. * * @return the value * @since Commons Collections 3.1 */ protected T getValue() { return value; } /** * Sets the value of the node. * * @param value the value * @since Commons Collections 3.1 */ protected void setValue(T value) { this.value = value; } /** * Gets the previous node. * * @return the previous node * @since Commons Collections 3.1 */ protected Node getPreviousNode() { return previous; } /** * Sets the previous node. * * @param previous the previous node * @since Commons Collections 3.1 */ protected void setPreviousNode(Node previous) { this.previous = previous; } /** * Gets the next node. * * @return the next node * @since Commons Collections 3.1 */ protected Node getNextNode() { return next; } /** * Sets the next node. * * @param next the next node * @since Commons Collections 3.1 */ protected void setNextNode(Node next) { this.next = next; } } //----------------------------------------------------------------------- /** * A list iterator over the linked list. */ protected static class LinkedListIterator implements ListIterator, OrderedIterator { /** * The parent list */ protected final AbstractLinkedList parent; /** * The node that will be returned by {@link #next()}. If this is equal * to {@link AbstractLinkedList#header} then there are no more values to return. */ protected Node next; /** * The index of {@link #next}. */ protected int nextIndex; /** * The last node that was returned by {@link #next()} or {@link * #previous()}. Set to null if {@link #next()} or {@link * #previous()} haven't been called, or if the node has been removed * with {@link #remove()} or a new node added with {@link #add(Object)}. * Should be accessed through {@link #getLastNodeReturned()} to enforce * this behaviour. */ protected Node current; /** * The modification count that the list is expected to have. If the list * doesn't have this count, then a * {@link java.util.ConcurrentModificationException} may be thrown by * the operations. */ protected int expectedModCount; /** * Create a ListIterator for a list. * * @param parent the parent list * @param fromIndex the index to start at */ protected LinkedListIterator(AbstractLinkedList parent, int fromIndex) throws IndexOutOfBoundsException { super(); this.parent = parent; this.expectedModCount = parent.modCount; this.next = parent.getNode(fromIndex, true); this.nextIndex = fromIndex; } /** * Checks the modification count of the list is the value that this * object expects. * * @throws ConcurrentModificationException * If the list's modification * count isn't the value that was expected. */ protected void checkModCount() { if (parent.modCount != expectedModCount) { throw new ConcurrentModificationException(); } } /** * Gets the last node returned. * * @throws IllegalStateException If {@link #next()} or * {@link #previous()} haven't been called, or if the node has been removed * with {@link #remove()} or a new node added with {@link #add(Object)}. */ protected Node getLastNodeReturned() throws IllegalStateException { if (current == null) { throw new IllegalStateException(); } return current; } public boolean hasNext() { return next != parent.header; } public E next() { checkModCount(); if (!hasNext()) { throw new NoSuchElementException("No element at index " + nextIndex + "."); } E value = next.getValue(); current = next; next = next.next; nextIndex++; return value; } public boolean hasPrevious() { return next.previous != parent.header; } public E previous() { checkModCount(); if (!hasPrevious()) { throw new NoSuchElementException("Already at start of list."); } next = next.previous; E value = next.getValue(); current = next; nextIndex--; return value; } public int nextIndex() { return nextIndex; } public int previousIndex() { // not normally overridden, as relative to nextIndex() return nextIndex() - 1; } public void remove() { checkModCount(); parent.removeNode(getLastNodeReturned()); current = null; nextIndex--; expectedModCount++; } public void set(E obj) { checkModCount(); getLastNodeReturned().setValue(obj); } public void add(E obj) { checkModCount(); parent.addNodeBefore(next, obj); current = null; nextIndex++; expectedModCount++; } } //----------------------------------------------------------------------- /** * A list iterator over the linked sub list. */ protected static class LinkedSubListIterator extends LinkedListIterator { /** * The parent list */ protected final LinkedSubList sub; protected LinkedSubListIterator(LinkedSubList sub, int startIndex) { super(sub.parent, startIndex + sub.offset); this.sub = sub; } public boolean hasNext() { return (nextIndex() < sub.size); } public boolean hasPrevious() { return (previousIndex() >= 0); } public int nextIndex() { return (super.nextIndex() - sub.offset); } public void add(E obj) { super.add(obj); sub.expectedModCount = parent.modCount; sub.size++; } public void remove() { super.remove(); sub.expectedModCount = parent.modCount; sub.size--; } } //----------------------------------------------------------------------- /** * The sublist implementation for AbstractLinkedList. */ protected static class LinkedSubList extends AbstractList { /** * The main list */ private AbstractLinkedList parent; /** * Offset from the main list */ private int offset; /** * Sublist size */ private int size; /** * Sublist modCount */ private int expectedModCount; protected LinkedSubList(AbstractLinkedList parent, int fromIndex, int toIndex) { if (fromIndex < 0) { throw new IndexOutOfBoundsException("fromIndex = " + fromIndex); } if (toIndex > parent.size()) { throw new IndexOutOfBoundsException("toIndex = " + toIndex); } if (fromIndex > toIndex) { throw new IllegalArgumentException("fromIndex(" + fromIndex + ") > toIndex(" + toIndex + ")"); } this.parent = parent; this.offset = fromIndex; this.size = toIndex - fromIndex; this.expectedModCount = parent.modCount; } public int size() { checkModCount(); return size; } public E get(int index) { rangeCheck(index, size); checkModCount(); return parent.get(index + offset); } public void add(int index, E obj) { rangeCheck(index, size + 1); checkModCount(); parent.add(index + offset, obj); expectedModCount = parent.modCount; size++; LinkedSubList.this.modCount++; } public E remove(int index) { rangeCheck(index, size); checkModCount(); E result = parent.remove(index + offset); expectedModCount = parent.modCount; size--; LinkedSubList.this.modCount++; return result; } public boolean addAll(Collection coll) { return addAll(size, coll); } public boolean addAll(int index, Collection coll) { rangeCheck(index, size + 1); int cSize = coll.size(); if (cSize == 0) { return false; } checkModCount(); parent.addAll(offset + index, coll); expectedModCount = parent.modCount; size += cSize; LinkedSubList.this.modCount++; return true; } public E set(int index, E obj) { rangeCheck(index, size); checkModCount(); return parent.set(index + offset, obj); } public void clear() { checkModCount(); Iterator it = iterator(); while (it.hasNext()) { it.next(); it.remove(); } } public Iterator iterator() { checkModCount(); return parent.createSubListIterator(this); } public ListIterator listIterator(final int index) { rangeCheck(index, size + 1); checkModCount(); return parent.createSubListListIterator(this, index); } public List subList(int fromIndexInclusive, int toIndexExclusive) { return new LinkedSubList(parent, fromIndexInclusive + offset, toIndexExclusive + offset); } protected void rangeCheck(int index, int beyond) { if (index < 0 || index >= beyond) { throw new IndexOutOfBoundsException("Index '" + index + "' out of bounds for size '" + size + "'"); } } protected void checkModCount() { if (parent.modCount != expectedModCount) { throw new ConcurrentModificationException(); } } } } collections-generic-4.01/src/java/org/apache/commons/collections15/list/LazyList.java0000644000175000017500000001146110464140754031054 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.list; import org.apache.commons.collections15.Factory; import java.util.List; /** * Decorates another List to create objects in the list on demand. *

      * When the {@link #get(int)} method is called with an index greater than * the size of the list, the list will automatically grow in size and return * a new object from the specified factory. The gaps will be filled by null. * If a get method call encounters a null, it will be replaced with a new * object from the factory. Thus this list is unsuitable for storing null * objects. *

      * For instance: *

      *

       * Factory factory = new Factory() {
       *     public Object create() {
       *         return new Date();
       *     }
       * }
       * List lazy = LazyList.decorate(new ArrayList(), factory);
       * Object obj = lazy.get(3);
       * 
      *

      * After the above code is executed, obj will contain * a new Date instance. Furthermore, that Date * instance is the fourth element in the list. The first, second, * and third element are all set to null. *

      * This class is Serializable from Commons Collections 3.1. * * @author Stephen Colebourne * @author Arron Bates * @author Paul Jack * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:32 $ * @since Commons Collections 3.0 */ public class LazyList extends AbstractSerializableListDecorator { /** * Serialization version */ private static final long serialVersionUID = -1708388017160694542L; /** * The factory to use to lazily instantiate the objects */ protected final Factory factory; /** * Factory method to create a lazily instantiating list. * * @param list the list to decorate, must not be null * @param factory the factory to use for creation, must not be null * @throws IllegalArgumentException if list or factory is null */ public static List decorate(List list, Factory factory) { return new LazyList(list, factory); } //----------------------------------------------------------------------- /** * Constructor that wraps (not copies). * * @param list the list to decorate, must not be null * @param factory the factory to use for creation, must not be null * @throws IllegalArgumentException if list or factory is null */ protected LazyList(List list, Factory factory) { super(list); if (factory == null) { throw new IllegalArgumentException("Factory must not be null"); } this.factory = factory; } //----------------------------------------------------------------------- /** * Decorate the get method to perform the lazy behaviour. *

      * If the requested index is greater than the current size, the list will * grow to the new size and a new object will be returned from the factory. * Indexes in-between the old size and the requested size are left with a * placeholder that is replaced with a factory object when requested. * * @param index the index to retrieve */ public E get(int index) { int size = getList().size(); if (index < size) { // within bounds, get the object E object = getList().get(index); if (object == null) { // item is a place holder, create new one, set and return object = factory.create(); getList().set(index, object); return object; } else { // good and ready to go return object; } } else { // we have to grow the list for (int i = size; i < index; i++) { getList().add(null); } // create our last object, set and return E object = factory.create(); getList().add(object); return object; } } public List subList(int fromIndex, int toIndex) { List sub = getList().subList(fromIndex, toIndex); return new LazyList(sub, factory); } } collections-generic-4.01/src/java/org/apache/commons/collections15/list/FastArrayList.java0000644000175000017500000010724410464140765032040 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.list; import java.util.*; /** *

      A customized implementation of java.util.ArrayList designed * to operate in a multithreaded environment where the large majority of * method calls are read-only, instead of structural changes. When operating * in "fast" mode, read calls are non-synchronized and write calls perform the * following steps:

      *
        *
      • Clone the existing collection *
      • Perform the modification on the clone *
      • Replace the existing collection with the (modified) clone *
      *

      When first created, objects of this class default to "slow" mode, where * all accesses of any type are synchronized but no cloning takes place. This * is appropriate for initially populating the collection, followed by a switch * to "fast" mode (by calling setFast(true)) after initialization * is complete.

      *

      *

      NOTE: If you are creating and accessing an * ArrayList only within a single thread, you should use * java.util.ArrayList directly (with no synchronization), for * maximum performance.

      *

      *

      NOTE: This class is not cross-platform. * Using it may cause unexpected failures on some architectures. * It suffers from the same problems as the double-checked locking idiom. * In particular, the instruction that clones the internal collection and the * instruction that sets the internal reference to the clone can be executed * or perceived out-of-order. This means that any read operation might fail * unexpectedly, as it may be reading the state of the internal collection * before the internal collection is fully formed. * For more information on the double-checked locking idiom, see the * * Double-Checked Locking Idiom Is Broken Declaration.

      * * @author Matt Hall, John Watkinson, Craig R. McClanahan * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:32 $ * @since Commons Collections 1.0 */ public class FastArrayList extends ArrayList { // ----------------------------------------------------------- Constructors /** * Construct a an empty list. */ public FastArrayList() { super(); this.list = new ArrayList(); } /** * Construct an empty list with the specified capacity. * * @param capacity The initial capacity of the empty list */ public FastArrayList(int capacity) { super(); this.list = new ArrayList(capacity); } /** * Construct a list containing the elements of the specified collection, * in the order they are returned by the collection's iterator. * * @param collection The collection whose elements initialize the contents * of this list */ public FastArrayList(Collection collection) { super(); this.list = new ArrayList(collection); } // ----------------------------------------------------- Instance Variables /** * The underlying list we are managing. */ protected ArrayList list = null; // ------------------------------------------------------------- Properties /** * Are we operating in "fast" mode? */ protected boolean fast = false; /** * Returns true if this list is operating in fast mode. * * @return true if this list is operating in fast mode */ public boolean getFast() { return (this.fast); } /** * Sets whether this list will operate in fast mode. * * @param fast true if the list should operate in fast mode */ public void setFast(boolean fast) { this.fast = fast; } // --------------------------------------------------------- Public Methods /** * Appends the specified element to the end of this list. * * @param element The element to be appended */ public boolean add(E element) { if (fast) { synchronized (this) { ArrayList temp = (ArrayList) list.clone(); boolean result = temp.add(element); list = temp; return (result); } } else { synchronized (list) { return (list.add(element)); } } } /** * Insert the specified element at the specified position in this list, * and shift all remaining elements up one position. * * @param index Index at which to insert this element * @param element The element to be inserted * @throws IndexOutOfBoundsException if the index is out of range */ public void add(int index, E element) { if (fast) { synchronized (this) { ArrayList temp = (ArrayList) list.clone(); temp.add(index, element); list = temp; } } else { synchronized (list) { list.add(index, element); } } } /** * Append all of the elements in the specified Collection to the end * of this list, in the order that they are returned by the specified * Collection's Iterator. * * @param collection The collection to be appended */ public boolean addAll(Collection collection) { if (fast) { synchronized (this) { ArrayList temp = (ArrayList) list.clone(); boolean result = temp.addAll(collection); list = temp; return (result); } } else { synchronized (list) { return (list.addAll(collection)); } } } /** * Insert all of the elements in the specified Collection at the specified * position in this list, and shift any previous elements upwards as * needed. * * @param index Index at which insertion takes place * @param collection The collection to be added * @throws IndexOutOfBoundsException if the index is out of range */ public boolean addAll(int index, Collection collection) { if (fast) { synchronized (this) { ArrayList temp = (ArrayList) list.clone(); boolean result = temp.addAll(index, collection); list = temp; return (result); } } else { synchronized (list) { return (list.addAll(index, collection)); } } } /** * Remove all of the elements from this list. The list will be empty * after this call returns. * * @throws UnsupportedOperationException if clear() * is not supported by this list */ public void clear() { if (fast) { synchronized (this) { ArrayList temp = (ArrayList) list.clone(); temp.clear(); list = temp; } } else { synchronized (list) { list.clear(); } } } /** * Return a shallow copy of this FastArrayList instance. * The elements themselves are not copied. */ public Object clone() { FastArrayList results = null; if (fast) { results = new FastArrayList(list); } else { synchronized (list) { results = new FastArrayList(list); } } results.setFast(getFast()); return (results); } /** * Return true if this list contains the specified element. * * @param element The element to test for */ public boolean contains(Object element) { if (fast) { return (list.contains(element)); } else { synchronized (list) { return (list.contains(element)); } } } /** * Return true if this list contains all of the elements * in the specified Collection. * * @param collection Collection whose elements are to be checked */ public boolean containsAll(Collection collection) { if (fast) { return (list.containsAll(collection)); } else { synchronized (list) { return (list.containsAll(collection)); } } } /** * Increase the capacity of this ArrayList instance, if * necessary, to ensure that it can hold at least the number of elements * specified by the minimum capacity argument. * * @param capacity The new minimum capacity */ public void ensureCapacity(int capacity) { if (fast) { synchronized (this) { ArrayList temp = (ArrayList) list.clone(); temp.ensureCapacity(capacity); list = temp; } } else { synchronized (list) { list.ensureCapacity(capacity); } } } /** * Compare the specified object with this list for equality. This * implementation uses exactly the code that is used to define the * list equals function in the documentation for the * List.equals method. * * @param o Object to be compared to this list */ public boolean equals(Object o) { // Simple tests that require no synchronization if (o == this) return (true); else if (!(o instanceof List)) return (false); List lo = (List) o; // Compare the sets of elements for equality if (fast) { ListIterator li1 = list.listIterator(); ListIterator li2 = lo.listIterator(); while (li1.hasNext() && li2.hasNext()) { Object o1 = li1.next(); Object o2 = li2.next(); if (!(o1 == null ? o2 == null : o1.equals(o2))) return (false); } return (!(li1.hasNext() || li2.hasNext())); } else { synchronized (list) { ListIterator li1 = list.listIterator(); ListIterator li2 = lo.listIterator(); while (li1.hasNext() && li2.hasNext()) { Object o1 = li1.next(); Object o2 = li2.next(); if (!(o1 == null ? o2 == null : o1.equals(o2))) return (false); } return (!(li1.hasNext() || li2.hasNext())); } } } /** * Return the element at the specified position in the list. * * @param index The index of the element to return * @throws IndexOutOfBoundsException if the index is out of range */ public E get(int index) { if (fast) { return (list.get(index)); } else { synchronized (list) { return (list.get(index)); } } } /** * Return the hash code value for this list. This implementation uses * exactly the code that is used to define the list hash function in the * documentation for the List.hashCode method. */ public int hashCode() { if (fast) { int hashCode = 1; java.util.Iterator i = list.iterator(); while (i.hasNext()) { Object o = i.next(); hashCode = 31 * hashCode + (o == null ? 0 : o.hashCode()); } return (hashCode); } else { synchronized (list) { int hashCode = 1; java.util.Iterator i = list.iterator(); while (i.hasNext()) { Object o = i.next(); hashCode = 31 * hashCode + (o == null ? 0 : o.hashCode()); } return (hashCode); } } } /** * Search for the first occurrence of the given argument, testing * for equality using the equals() method, and return * the corresponding index, or -1 if the object is not found. * * @param element The element to search for */ public int indexOf(Object element) { if (fast) { return (list.indexOf(element)); } else { synchronized (list) { return (list.indexOf(element)); } } } /** * Test if this list has no elements. */ public boolean isEmpty() { if (fast) { return (list.isEmpty()); } else { synchronized (list) { return (list.isEmpty()); } } } /** * Return an iterator over the elements in this list in proper sequence. *

      * IMPLEMENTATION NOTE - If the list is operating in fast * mode, an Iterator is returned, and a structural modification to the * list is made, then the Iterator will continue over the previous contents * of the list (at the time that the Iterator was created), rather than * failing due to concurrent modifications. */ public Iterator iterator() { if (fast) { return new ListIter(0); } else { return list.iterator(); } } /** * Search for the last occurrence of the given argument, testing * for equality using the equals() method, and return * the corresponding index, or -1 if the object is not found. * * @param element The element to search for */ public int lastIndexOf(Object element) { if (fast) { return (list.lastIndexOf(element)); } else { synchronized (list) { return (list.lastIndexOf(element)); } } } /** * Return an iterator of the elements of this list, in proper sequence. * See the implementation note on iterator(). */ public ListIterator listIterator() { if (fast) { return new ListIter(0); } else { return list.listIterator(); } } /** * Return an iterator of the elements of this list, in proper sequence, * starting at the specified position. * See the implementation note on iterator(). * * @param index The starting position of the iterator to return * @throws IndexOutOfBoundsException if the index is out of range */ public ListIterator listIterator(int index) { if (fast) { return new ListIter(index); } else { return list.listIterator(index); } } /** * Remove the element at the specified position in the list, and shift * any subsequent elements down one position. * * @param index Index of the element to be removed * @throws IndexOutOfBoundsException if the index is out of range */ public E remove(int index) { if (fast) { synchronized (this) { ArrayList temp = (ArrayList) list.clone(); E result = temp.remove(index); list = temp; return (result); } } else { synchronized (list) { return (list.remove(index)); } } } /** * Remove the first occurrence of the specified element from the list, * and shift any subsequent elements down one position. * * @param element Element to be removed */ public boolean remove(Object element) { if (fast) { synchronized (this) { ArrayList temp = (ArrayList) list.clone(); boolean result = temp.remove(element); list = temp; return (result); } } else { synchronized (list) { return (list.remove(element)); } } } /** * Remove from this collection all of its elements that are contained * in the specified collection. * * @param collection Collection containing elements to be removed * @throws UnsupportedOperationException if this optional operation * is not supported by this list */ public boolean removeAll(Collection collection) { if (fast) { synchronized (this) { ArrayList temp = (ArrayList) list.clone(); boolean result = temp.removeAll(collection); list = temp; return (result); } } else { synchronized (list) { return (list.removeAll(collection)); } } } /** * Remove from this collection all of its elements except those that are * contained in the specified collection. * * @param collection Collection containing elements to be retained * @throws UnsupportedOperationException if this optional operation * is not supported by this list */ public boolean retainAll(Collection collection) { if (fast) { synchronized (this) { ArrayList temp = (ArrayList) list.clone(); boolean result = temp.retainAll(collection); list = temp; return (result); } } else { synchronized (list) { return (list.retainAll(collection)); } } } /** * Replace the element at the specified position in this list with * the specified element. Returns the previous object at that position. *

      * IMPLEMENTATION NOTE - This operation is specifically * documented to not be a structural change, so it is safe to be performed * without cloning. * * @param index Index of the element to replace * @param element The new element to be stored * @throws IndexOutOfBoundsException if the index is out of range */ public E set(int index, E element) { if (fast) { return (list.set(index, element)); } else { synchronized (list) { return (list.set(index, element)); } } } /** * Return the number of elements in this list. */ public int size() { if (fast) { return (list.size()); } else { synchronized (list) { return (list.size()); } } } /** * Return a view of the portion of this list between fromIndex * (inclusive) and toIndex (exclusive). The returned list is backed * by this list, so non-structural changes in the returned list are * reflected in this list. The returned list supports * all of the optional list operations supported by this list. * * @param fromIndex The starting index of the sublist view * @param toIndex The index after the end of the sublist view * @throws IndexOutOfBoundsException if an index is out of range */ public List subList(int fromIndex, int toIndex) { if (fast) { return new SubList(fromIndex, toIndex); } else { return list.subList(fromIndex, toIndex); } } /** * Return an array containing all of the elements in this list in the * correct order. */ public Object[] toArray() { if (fast) { return (list.toArray()); } else { synchronized (list) { return (list.toArray()); } } } /** * Return an array containing all of the elements in this list in the * correct order. The runtime type of the returned array is that of * the specified array. If the list fits in the specified array, it is * returned therein. Otherwise, a new array is allocated with the * runtime type of the specified array, and the size of this list. * * @param array Array defining the element type of the returned list * @throws ArrayStoreException if the runtime type of array * is not a supertype of the runtime type of every element in this list */ public T[] toArray(T[] array) { if (fast) { return (list.toArray(array)); } else { synchronized (list) { return (list.toArray(array)); } } } /** * Return a String representation of this object. */ public String toString() { StringBuffer sb = new StringBuffer("FastArrayList["); sb.append(list.toString()); sb.append("]"); return (sb.toString()); } /** * Trim the capacity of this ArrayList instance to be the * list's current size. An application can use this operation to minimize * the storage of an ArrayList instance. */ public void trimToSize() { if (fast) { synchronized (this) { ArrayList temp = (ArrayList) list.clone(); temp.trimToSize(); list = temp; } } else { synchronized (list) { list.trimToSize(); } } } private class SubList implements List { private int first; private int last; private List expected; public SubList(int first, int last) { this.first = first; this.last = last; this.expected = list; } private List get(List l) { if (list != expected) { throw new ConcurrentModificationException(); } return l.subList(first, last); } public void clear() { if (fast) { synchronized (FastArrayList.this) { ArrayList temp = (ArrayList) list.clone(); get(temp).clear(); last = first; list = temp; expected = temp; } } else { synchronized (list) { get(expected).clear(); } } } public boolean remove(Object o) { if (fast) { synchronized (FastArrayList.this) { ArrayList temp = (ArrayList) list.clone(); boolean r = get(temp).remove(o); if (r) last--; list = temp; expected = temp; return r; } } else { synchronized (list) { return get(expected).remove(o); } } } public boolean removeAll(Collection o) { if (fast) { synchronized (FastArrayList.this) { ArrayList temp = (ArrayList) list.clone(); List sub = get(temp); boolean r = sub.removeAll(o); if (r) last = first + sub.size(); list = temp; expected = temp; return r; } } else { synchronized (list) { return get(expected).removeAll(o); } } } public boolean retainAll(Collection o) { if (fast) { synchronized (FastArrayList.this) { ArrayList temp = (ArrayList) list.clone(); List sub = get(temp); boolean r = sub.retainAll(o); if (r) last = first + sub.size(); list = temp; expected = temp; return r; } } else { synchronized (list) { return get(expected).retainAll(o); } } } public int size() { if (fast) { return get(expected).size(); } else { synchronized (list) { return get(expected).size(); } } } public boolean isEmpty() { if (fast) { return get(expected).isEmpty(); } else { synchronized (list) { return get(expected).isEmpty(); } } } public boolean contains(Object o) { if (fast) { return get(expected).contains(o); } else { synchronized (list) { return get(expected).contains(o); } } } public boolean containsAll(Collection o) { if (fast) { return get(expected).containsAll(o); } else { synchronized (list) { return get(expected).containsAll(o); } } } public T[] toArray(T[] o) { if (fast) { return get(expected).toArray(o); } else { synchronized (list) { return get(expected).toArray(o); } } } public Object[] toArray() { if (fast) { return get(expected).toArray(); } else { synchronized (list) { return get(expected).toArray(); } } } public boolean equals(Object o) { if (o == this) return true; if (fast) { return get(expected).equals(o); } else { synchronized (list) { return get(expected).equals(o); } } } public int hashCode() { if (fast) { return get(expected).hashCode(); } else { synchronized (list) { return get(expected).hashCode(); } } } public boolean add(E o) { if (fast) { synchronized (FastArrayList.this) { ArrayList temp = (ArrayList) list.clone(); boolean r = get(temp).add(o); if (r) last++; list = temp; expected = temp; return r; } } else { synchronized (list) { return get(expected).add(o); } } } public boolean addAll(Collection o) { if (fast) { synchronized (FastArrayList.this) { ArrayList temp = (ArrayList) list.clone(); boolean r = get(temp).addAll(o); if (r) last += o.size(); list = temp; expected = temp; return r; } } else { synchronized (list) { return get(expected).addAll(o); } } } public void add(int i, E o) { if (fast) { synchronized (FastArrayList.this) { ArrayList temp = (ArrayList) list.clone(); get(temp).add(i, o); last++; list = temp; expected = temp; } } else { synchronized (list) { get(expected).add(i, o); } } } public boolean addAll(int i, Collection o) { if (fast) { synchronized (FastArrayList.this) { ArrayList temp = (ArrayList) list.clone(); boolean r = get(temp).addAll(i, o); list = temp; if (r) last += o.size(); expected = temp; return r; } } else { synchronized (list) { return get(expected).addAll(i, o); } } } public E remove(int i) { if (fast) { synchronized (FastArrayList.this) { ArrayList temp = (ArrayList) list.clone(); E o = get(temp).remove(i); last--; list = temp; expected = temp; return o; } } else { synchronized (list) { return get(expected).remove(i); } } } public E set(int i, E a) { if (fast) { synchronized (FastArrayList.this) { ArrayList temp = (ArrayList) list.clone(); E o = get(temp).set(i, a); list = temp; expected = temp; return o; } } else { synchronized (list) { return get(expected).set(i, a); } } } public Iterator iterator() { return new SubListIter(0); } public ListIterator listIterator() { return new SubListIter(0); } public ListIterator listIterator(int i) { return new SubListIter(i); } public E get(int i) { if (fast) { return get(expected).get(i); } else { synchronized (list) { return get(expected).get(i); } } } public int indexOf(Object o) { if (fast) { return get(expected).indexOf(o); } else { synchronized (list) { return get(expected).indexOf(o); } } } public int lastIndexOf(Object o) { if (fast) { return get(expected).lastIndexOf(o); } else { synchronized (list) { return get(expected).lastIndexOf(o); } } } public List subList(int f, int l) { if (list != expected) { throw new ConcurrentModificationException(); } return new SubList(first + f, f + l); } private class SubListIter implements ListIterator { private List expected; private ListIterator iter; private int lastReturnedIndex = -1; public SubListIter(int i) { this.expected = list; this.iter = SubList.this.get(expected).listIterator(i); } private void checkMod() { if (list != expected) { throw new ConcurrentModificationException(); } } List get() { return SubList.this.get(expected); } public boolean hasNext() { checkMod(); return iter.hasNext(); } public E next() { checkMod(); lastReturnedIndex = iter.nextIndex(); return iter.next(); } public boolean hasPrevious() { checkMod(); return iter.hasPrevious(); } public E previous() { checkMod(); lastReturnedIndex = iter.previousIndex(); return iter.previous(); } public int previousIndex() { checkMod(); return iter.previousIndex(); } public int nextIndex() { checkMod(); return iter.nextIndex(); } public void remove() { checkMod(); if (lastReturnedIndex < 0) { throw new IllegalStateException(); } get().remove(lastReturnedIndex); last--; expected = list; iter = get().listIterator(previousIndex()); lastReturnedIndex = -1; } public void set(E o) { checkMod(); if (lastReturnedIndex < 0) { throw new IllegalStateException(); } get().set(lastReturnedIndex, o); expected = list; iter = get().listIterator(previousIndex() + 1); } public void add(E o) { checkMod(); int i = nextIndex(); get().add(i, o); last++; iter = get().listIterator(i + 1); lastReturnedIndex = 1; } } } private class ListIter implements ListIterator { private List expected; private ListIterator iter; private int lastReturnedIndex = -1; public ListIter(int i) { this.expected = list; this.iter = get().listIterator(i); } private void checkMod() { if (list != expected) { throw new ConcurrentModificationException(); } } List get() { return expected; } public boolean hasNext() { checkMod(); return iter.hasNext(); } public E next() { checkMod(); lastReturnedIndex = iter.nextIndex(); return iter.next(); } public boolean hasPrevious() { checkMod(); return iter.hasPrevious(); } public E previous() { checkMod(); lastReturnedIndex = iter.previousIndex(); return iter.previous(); } public int previousIndex() { checkMod(); return iter.previousIndex(); } public int nextIndex() { checkMod(); return iter.nextIndex(); } public void remove() { checkMod(); if (lastReturnedIndex < 0) { throw new IllegalStateException(); } get().remove(lastReturnedIndex); expected = list; iter = get().listIterator(previousIndex()); lastReturnedIndex = -1; } public void set(E o) { checkMod(); if (lastReturnedIndex < 0) { throw new IllegalStateException(); } get().set(lastReturnedIndex, o); expected = list; iter = get().listIterator(previousIndex() + 1); } public void add(E o) { checkMod(); int i = nextIndex(); get().add(i, o); iter = get().listIterator(i + 1); lastReturnedIndex = -1; } } } collections-generic-4.01/src/java/org/apache/commons/collections15/list/package.html0000644000175000017500000000335010464140762030714 0ustar giovannigiovanni

      This package contains implementations of the {@link java.util.List List} interface.

      The following implementations are provided in the package:

      • TreeList - a list that is optimised for insertions and removals at any index in the list
      • CursorableLinkedList - a list that can be modified while it's listIterator (cursor) is being used
      • NodeCachingLinkedList - a linked list that caches the storage nodes for a performance gain

      The following decorators are provided in the package:

      • Synchronized - synchronizes method access for multi-threaded environments
      • Unmodifiable - ensures the collection cannot be altered
      • Predicated - ensures that only elements that are valid according to a predicate can be added
      • Typed - ensures that only elements that are of a specific type can be added
      • Transformed - transforms each element added
      • FixedSize - ensures that the size of the list cannot change
      • Lazy - creates objects in the list on demand
      • SetUnique - a list that avoids duplicate entries like a Set
      collections-generic-4.01/src/java/org/apache/commons/collections15/list/FixedSizeList.java0000644000175000017500000001174110464140761032026 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.list; import org.apache.commons.collections15.BoundedCollection; import org.apache.commons.collections15.iterators.AbstractListIteratorDecorator; import org.apache.commons.collections15.iterators.UnmodifiableIterator; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.ListIterator; /** * Decorates another List to fix the size preventing add/remove. *

      * The add, remove, clear and retain operations are unsupported. * The set method is allowed (as it doesn't change the list size). *

      * This class is Serializable from Commons Collections 3.1. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @author Matt Hall, John Watkinson, Paul Jack * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:32 $ * @since Commons Collections 3.0 */ public class FixedSizeList extends AbstractSerializableListDecorator implements BoundedCollection { /** * Serialization version */ private static final long serialVersionUID = -2218010673611160319L; /** * Factory method to create a fixed size list. * * @param list the list to decorate, must not be null * @throws IllegalArgumentException if list is null */ public static List decorate(List list) { return new FixedSizeList(list); } //----------------------------------------------------------------------- /** * Constructor that wraps (not copies). * * @param list the list to decorate, must not be null * @throws IllegalArgumentException if list is null */ protected FixedSizeList(List list) { super(list); } //----------------------------------------------------------------------- public boolean add(E object) { throw new UnsupportedOperationException("List is fixed size"); } public void add(int index, E object) { throw new UnsupportedOperationException("List is fixed size"); } public boolean addAll(Collection coll) { throw new UnsupportedOperationException("List is fixed size"); } public boolean addAll(int index, Collection coll) { throw new UnsupportedOperationException("List is fixed size"); } public void clear() { throw new UnsupportedOperationException("List is fixed size"); } public E get(int index) { return getList().get(index); } public int indexOf(Object object) { return getList().indexOf(object); } public Iterator iterator() { return UnmodifiableIterator.decorate(getCollection().iterator()); } public int lastIndexOf(Object object) { return getList().lastIndexOf(object); } public ListIterator listIterator() { return new FixedSizeListIterator(getList().listIterator(0)); } public ListIterator listIterator(int index) { return new FixedSizeListIterator(getList().listIterator(index)); } public E remove(int index) { throw new UnsupportedOperationException("List is fixed size"); } public boolean remove(Object object) { throw new UnsupportedOperationException("List is fixed size"); } public boolean removeAll(Collection coll) { throw new UnsupportedOperationException("List is fixed size"); } public boolean retainAll(Collection coll) { throw new UnsupportedOperationException("List is fixed size"); } public E set(int index, E object) { return getList().set(index, object); } public List subList(int fromIndex, int toIndex) { List sub = getList().subList(fromIndex, toIndex); return new FixedSizeList(sub); } /** * List iterator that only permits changes via set() */ static class FixedSizeListIterator extends AbstractListIteratorDecorator { protected FixedSizeListIterator(ListIterator iterator) { super(iterator); } public void remove() { throw new UnsupportedOperationException("List is fixed size"); } public void add(E object) { throw new UnsupportedOperationException("List is fixed size"); } } public boolean isFull() { return true; } public int maxSize() { return size(); } } collections-generic-4.01/src/java/org/apache/commons/collections15/PredicateUtils.java0000644000175000017500000005053710464140761031254 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2002-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15; import org.apache.commons.collections15.functors.*; import java.util.Collection; /** * PredicateUtils provides reference implementations and utilities * for the Predicate functor interface. The supplied predicates are: *

        *
      • Invoker - returns the result of a method call on the input object *
      • InstanceOf - true if the object is an instanceof a class *
      • Equal - true if the object equals() a specified object *
      • Identity - true if the object == a specified object *
      • Null - true if the object is null *
      • NotNull - true if the object is not null *
      • Unique - true if the object has not already been evaluated *
      • And/All - true if all of the predicates are true *
      • Or/Any - true if any of the predicates is true *
      • Either/One - true if only one of the predicate is true *
      • Neither/None - true if none of the predicates are true *
      • Not - true if the predicate is false, and vice versa *
      • Transformer - wraps a Transformer as a Predicate *
      • True - always return true *
      • False - always return false *
      • Exception - always throws an exception *
      • NullIsException/NullIsFalse/NullIsTrue - check for null input *
      • Transformed - transforms the input before calling the predicate *
      * All the supplied predicates are Serializable. * * @author Stephen Colebourne * @author Matt Hall, John Watkinson, Ola Berg * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:19 $ * @since Commons Collections 3.0 */ public class PredicateUtils { /** * This class is not normally instantiated. */ public PredicateUtils() { super(); } // Simple predicates //----------------------------------------------------------------------------- /** * Gets a Predicate that always throws an exception. * This could be useful during testing as a placeholder. * * @return the predicate * @see org.apache.commons.collections15.functors.ExceptionPredicate */ public static Predicate exceptionPredicate() { return ExceptionPredicate.INSTANCE; } /** * Gets a Predicate that always returns true. * * @return the predicate * @see org.apache.commons.collections15.functors.TruePredicate */ public static Predicate truePredicate() { return TruePredicate.getInstance(); } /** * Gets a Predicate that always returns false. * * @return the predicate * @see org.apache.commons.collections15.functors.FalsePredicate */ public static Predicate falsePredicate() { return FalsePredicate.getInstance(); } /** * Gets a Predicate that checks if the input object passed in is null. * * @return the predicate * @see org.apache.commons.collections15.functors.NullPredicate */ public static Predicate nullPredicate() { return NullPredicate.getInstance(); } /** * Gets a Predicate that checks if the input object passed in is not null. * * @return the predicate * @see org.apache.commons.collections15.functors.NotNullPredicate */ public static Predicate notNullPredicate() { return NotNullPredicate.getInstance(); } /** * Creates a Predicate that checks if the input object is equal to the * specified object using equals(). * * @param value the value to compare against * @return the predicate * @see org.apache.commons.collections15.functors.EqualPredicate */ public static Predicate equalPredicate(T value) { return EqualPredicate.getInstance(value); } /** * Creates a Predicate that checks if the input object is equal to the * specified object by identity. * * @param value the value to compare against * @return the predicate * @see org.apache.commons.collections15.functors.IdentityPredicate */ public static Predicate identityPredicate(T value) { return IdentityPredicate.getInstance(value); } /** * Creates a Predicate that checks if the object passed in is of * a particular type, using instanceof. A null input * object will return false. * * @param type the type to check for, may not be null * @return the predicate * @throws IllegalArgumentException if the class is null * @see org.apache.commons.collections15.functors.InstanceofPredicate */ @SuppressWarnings("unchecked") public static Predicate instanceofPredicate(Class type) { return InstanceofPredicate.getInstance(type); } /** * Creates a Predicate that returns true the first time an object is * encountered, and false if the same object is received * again. The comparison is by equals(). A null input object * is accepted and will return true the first time, and false subsequently * as well. * * @return the predicate * @see org.apache.commons.collections15.functors.UniquePredicate */ public static Predicate uniquePredicate() { // must return new instance each time return UniquePredicate.getInstance(); } /** * Creates a Predicate that invokes a method on the input object. * The method must return either a boolean or a non-null Boolean, * and have no parameters. If the input object is null, a * PredicateException is thrown. *

      * For example, PredicateUtils.invokerPredicate("isEmpty"); * will call the isEmpty method on the input object to * determine the predicate result. * * @param methodName the method name to call on the input object, may not be null * @return the predicate * @throws IllegalArgumentException if the methodName is null. * @see org.apache.commons.collections15.functors.InvokerTransformer * @see org.apache.commons.collections15.functors.TransformerPredicate */ public static Predicate invokerPredicate(String methodName) { // reuse transformer as it has caching - this is lazy really, should have inner class here return asPredicate(InvokerTransformer.getInstance(methodName)); } /** * Creates a Predicate that invokes a method on the input object. * The method must return either a boolean or a non-null Boolean, * and have no parameters. If the input object is null, a * PredicateException is thrown. *

      * For example, PredicateUtils.invokerPredicate("isEmpty"); * will call the isEmpty method on the input object to * determine the predicate result. * * @param methodName the method name to call on the input object, may not be null * @param paramTypes the parameter types * @param args the arguments * @return the predicate * @throws IllegalArgumentException if the method name is null * @throws IllegalArgumentException if the paramTypes and args don't match * @see org.apache.commons.collections15.functors.InvokerTransformer * @see org.apache.commons.collections15.functors.TransformerPredicate */ public static Predicate invokerPredicate(String methodName, Class[] paramTypes, Object[] args) { // reuse transformer as it has caching - this is lazy really, should have inner class here return asPredicate(InvokerTransformer.getInstance(methodName, paramTypes, args)); } // Boolean combinations //----------------------------------------------------------------------------- /** * Create a new Predicate that returns true only if both of the specified * predicates are true. * * @param predicate1 the first predicate, may not be null * @param predicate2 the second predicate, may not be null * @return the and predicate * @throws IllegalArgumentException if either predicate is null * @see org.apache.commons.collections15.functors.AndPredicate */ public static Predicate andPredicate(Predicate predicate1, Predicate predicate2) { return AndPredicate.getInstance(predicate1, predicate2); } /** * Create a new Predicate that returns true only if all of the specified * predicates are true. * * @param predicates an array of predicates to check, may not be null * @return the all predicate * @throws IllegalArgumentException if the predicates array is null * @throws IllegalArgumentException if the predicates array has less than 2 elements * @throws IllegalArgumentException if any predicate in the array is null * @see org.apache.commons.collections15.functors.AllPredicate */ public static Predicate allPredicate(Predicate ... predicates) { return AllPredicate.getInstance(predicates); } /** * Create a new Predicate that returns true only if all of the specified * predicates are true. The predicates are checked in iterator order. * * @param predicates a collection of predicates to check, may not be null * @return the all predicate * @throws IllegalArgumentException if the predicates collection is null * @throws IllegalArgumentException if the predicates collection has less than 2 elements * @throws IllegalArgumentException if any predicate in the collection is null * @see org.apache.commons.collections15.functors.AllPredicate */ public static Predicate allPredicate(Collection> predicates) { return AllPredicate.getInstance(predicates); } /** * Create a new Predicate that returns true if either of the specified * predicates are true. * * @param predicate1 the first predicate, may not be null * @param predicate2 the second predicate, may not be null * @return the or predicate * @throws IllegalArgumentException if either predicate is null * @see org.apache.commons.collections15.functors.OrPredicate */ public static Predicate orPredicate(Predicate predicate1, Predicate predicate2) { return OrPredicate.getInstance(predicate1, predicate2); } /** * Create a new Predicate that returns true if any of the specified * predicates are true. * * @param predicates an array of predicates to check, may not be null * @return the any predicate * @throws IllegalArgumentException if the predicates array is null * @throws IllegalArgumentException if the predicates array has less than 2 elements * @throws IllegalArgumentException if any predicate in the array is null * @see org.apache.commons.collections15.functors.AnyPredicate */ public static Predicate anyPredicate(Predicate ... predicates) { return AnyPredicate.getInstance(predicates); } /** * Create a new Predicate that returns true if any of the specified * predicates are true. The predicates are checked in iterator order. * * @param predicates a collection of predicates to check, may not be null * @return the any predicate * @throws IllegalArgumentException if the predicates collection is null * @throws IllegalArgumentException if the predicates collection has less than 2 elements * @throws IllegalArgumentException if any predicate in the collection is null * @see org.apache.commons.collections15.functors.AnyPredicate */ public static Predicate anyPredicate(Collection> predicates) { return AnyPredicate.getInstance(predicates); } /** * Create a new Predicate that returns true if one, but not both, of the * specified predicates are true. * * @param predicate1 the first predicate, may not be null * @param predicate2 the second predicate, may not be null * @return the either predicate * @throws IllegalArgumentException if either predicate is null * @see org.apache.commons.collections15.functors.OnePredicate */ @SuppressWarnings("unchecked") public static Predicate eitherPredicate(Predicate predicate1, Predicate predicate2) { return onePredicate(new Predicate[]{predicate1, predicate2}); } /** * Create a new Predicate that returns true if only one of the specified * predicates are true. * * @param predicates an array of predicates to check, may not be null * @return the one predicate * @throws IllegalArgumentException if the predicates array is null * @throws IllegalArgumentException if the predicates array has less than 2 elements * @throws IllegalArgumentException if any predicate in the array is null * @see org.apache.commons.collections15.functors.OnePredicate */ public static Predicate onePredicate(Predicate ... predicates) { return OnePredicate.getInstance(predicates); } /** * Create a new Predicate that returns true if only one of the specified * predicates are true. The predicates are checked in iterator order. * * @param predicates a collection of predicates to check, may not be null * @return the one predicate * @throws IllegalArgumentException if the predicates collection is null * @throws IllegalArgumentException if the predicates collection has less than 2 elements * @throws IllegalArgumentException if any predicate in the collection is null * @see org.apache.commons.collections15.functors.OnePredicate */ public static Predicate onePredicate(Collection> predicates) { return OnePredicate.getInstance(predicates); } /** * Create a new Predicate that returns true if neither of the specified * predicates are true. * * @param predicate1 the first predicate, may not be null * @param predicate2 the second predicate, may not be null * @return the neither predicate * @throws IllegalArgumentException if either predicate is null * @see org.apache.commons.collections15.functors.NonePredicate */ @SuppressWarnings("unchecked") public static Predicate neitherPredicate(Predicate predicate1, Predicate predicate2) { return nonePredicate(new Predicate[]{predicate1, predicate2}); } /** * Create a new Predicate that returns true if none of the specified * predicates are true. * * @param predicates an array of predicates to check, may not be null * @return the none predicate * @throws IllegalArgumentException if the predicates array is null * @throws IllegalArgumentException if the predicates array has less than 2 elements * @throws IllegalArgumentException if any predicate in the array is null * @see org.apache.commons.collections15.functors.NonePredicate */ public static Predicate nonePredicate(Predicate ... predicates) { return NonePredicate.getInstance(predicates); } /** * Create a new Predicate that returns true if none of the specified * predicates are true. The predicates are checked in iterator order. * * @param predicates a collection of predicates to check, may not be null * @return the none predicate * @throws IllegalArgumentException if the predicates collection is null * @throws IllegalArgumentException if the predicates collection has less than 2 elements * @throws IllegalArgumentException if any predicate in the collection is null * @see org.apache.commons.collections15.functors.NonePredicate */ public static Predicate nonePredicate(Collection> predicates) { return NonePredicate.getInstance(predicates); } /** * Create a new Predicate that returns true if the specified predicate * returns false and vice versa. * * @param predicate the predicate to not * @return the not predicate * @throws IllegalArgumentException if the predicate is null * @see org.apache.commons.collections15.functors.NotPredicate */ public static Predicate notPredicate(Predicate predicate) { return NotPredicate.getInstance(predicate); } // Adaptors //----------------------------------------------------------------------------- /** * Create a new Predicate that wraps a Transformer. The Transformer must * return either Boolean.TRUE or Boolean.FALSE otherwise a PredicateException * will be thrown. * * @param transformer the transformer to wrap, may not be null * @return the transformer wrapping predicate * @throws IllegalArgumentException if the transformer is null * @see org.apache.commons.collections15.functors.TransformerPredicate */ public static Predicate asPredicate(Transformer transformer) { return TransformerPredicate.getInstance(transformer); } // Null handlers //----------------------------------------------------------------------------- /** * Gets a Predicate that throws an exception if the input object is null, * otherwise it calls the specified Predicate. This allows null handling * behaviour to be added to Predicates that don't support nulls. * * @param predicate the predicate to wrap, may not be null * @return the predicate * @throws IllegalArgumentException if the predicate is null. * @see org.apache.commons.collections15.functors.NullIsExceptionPredicate */ public static Predicate nullIsExceptionPredicate(Predicate predicate) { return NullIsExceptionPredicate.getInstance(predicate); } /** * Gets a Predicate that returns false if the input object is null, otherwise * it calls the specified Predicate. This allows null handling behaviour to * be added to Predicates that don't support nulls. * * @param predicate the predicate to wrap, may not be null * @return the predicate * @throws IllegalArgumentException if the predicate is null. * @see org.apache.commons.collections15.functors.NullIsFalsePredicate */ public static Predicate nullIsFalsePredicate(Predicate predicate) { return NullIsFalsePredicate.getInstance(predicate); } /** * Gets a Predicate that returns true if the input object is null, otherwise * it calls the specified Predicate. This allows null handling behaviour to * be added to Predicates that don't support nulls. * * @param predicate the predicate to wrap, may not be null * @return the predicate * @throws IllegalArgumentException if the predicate is null. * @see org.apache.commons.collections15.functors.NullIsTruePredicate */ public static Predicate nullIsTruePredicate(Predicate predicate) { return NullIsTruePredicate.getInstance(predicate); } // Transformed //----------------------------------------------------------------------- /** * Creates a predicate that transforms the input object before passing it * to the predicate. * * @param transformer the transformer to call first * @param predicate the predicate to call with the result of the transform * @return the predicate * @throws IllegalArgumentException if the transformer or the predicate is null * @see org.apache.commons.collections15.functors.TransformedPredicate * @since Commons Collections 3.1 */ public static Predicate transformedPredicate(Transformer transformer, Predicate predicate) { return TransformedPredicate.getInstance(transformer, predicate); } } collections-generic-4.01/src/java/org/apache/commons/collections15/OrderedIterator.java0000644000175000017500000000301010464140754031413 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15; import java.util.Iterator; /** * Defines an iterator that operates over a ordered collections15. *

      * This iterator allows both forward and reverse iteration through the collection. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:19 $ * @since Commons Collections 3.0 */ public interface OrderedIterator extends Iterator { /** * Checks to see if there is a previous entry that can be iterated to. * * @return true if the iterator has a previous element */ boolean hasPrevious(); /** * Gets the previous element from the collection. * * @return the previous key in the iteration * @throws java.util.NoSuchElementException * if the iteration is finished */ E previous(); } collections-generic-4.01/src/java/org/apache/commons/collections15/bag/0000755000175000017500000000000011664401370026206 5ustar giovannigiovannicollections-generic-4.01/src/java/org/apache/commons/collections15/bag/TransformedBag.java0000644000175000017500000000730110464140755031754 0ustar giovannigiovanni// TODO: Not yet converted - deprecated (by me). /* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.bag; import org.apache.commons.collections15.Bag; import org.apache.commons.collections15.Transformer; import org.apache.commons.collections15.collection.TransformedCollection; import org.apache.commons.collections15.set.TransformedSet; import java.util.Set; /** * Decorates another Bag to transform objects that are added. *

      * The add methods are affected by this class. * Thus objects must be removed or searched for using their transformed form. * For example, if the transformation converts Strings to Integers, you must * use the Integer form to remove objects. *

      * This class is Serializable from Commons Collections 3.1. *

      * Note: This class cannot support generics without breaking the Collection contract. * * @author Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:19 $ * @since Commons Collections 3.0 */ public class TransformedBag extends TransformedCollection implements Bag { /** * Serialization version */ private static final long serialVersionUID = 5421170911299074185L; /** * Factory method to create a transforming bag. *

      * If there are any elements already in the bag being decorated, they * are NOT transformed. * * @param bag the bag to decorate, must not be null * @param transformer the transformer to use for conversion, must not be null * @return a new transformed Bag * @throws IllegalArgumentException if bag or transformer is null */ public static Bag decorate(Bag bag, Transformer transformer) { return new TransformedBag(bag, transformer); } //----------------------------------------------------------------------- /** * Constructor that wraps (not copies). *

      * If there are any elements already in the bag being decorated, they * are NOT transformed. * * @param bag the bag to decorate, must not be null * @param transformer the transformer to use for conversion, must not be null * @throws IllegalArgumentException if bag or transformer is null */ protected TransformedBag(Bag bag, Transformer transformer) { super(bag, transformer); } /** * Gets the decorated bag. * * @return the decorated bag */ protected Bag getBag() { return (Bag) collection; } //----------------------------------------------------------------------- public int getCount(Object object) { return getBag().getCount(object); } public boolean remove(Object object, int nCopies) { return getBag().remove(object, nCopies); } //----------------------------------------------------------------------- public boolean add(Object object, int nCopies) { object = transform(object); return getBag().add(object, nCopies); } public Set uniqueSet() { Set set = getBag().uniqueSet(); return TransformedSet.decorate(set, transformer); } } collections-generic-4.01/src/java/org/apache/commons/collections15/bag/SynchronizedSortedBag.java0000644000175000017500000000621710464140765033336 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.bag; import org.apache.commons.collections15.Bag; import org.apache.commons.collections15.SortedBag; import java.util.Comparator; /** * Decorates another SortedBag to synchronize its behaviour * for a multi-threaded environment. *

      * Methods are synchronized, then forwarded to the decorated bag. * Iterators must be separately synchronized around the loop. *

      * This class is Serializable from Commons Collections 3.1. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:19 $ * @since Commons Collections 3.0 */ public class SynchronizedSortedBag extends SynchronizedBag implements SortedBag { /** * Serialization version */ private static final long serialVersionUID = 722374056718497858L; /** * Factory method to create a synchronized sorted bag. * * @param bag the bag to decorate, must not be null * @return a new synchronized SortedBag * @throws IllegalArgumentException if bag is null */ public static SortedBag decorate(SortedBag bag) { return new SynchronizedSortedBag(bag); } //----------------------------------------------------------------------- /** * Constructor that wraps (not copies). * * @param bag the bag to decorate, must not be null * @throws IllegalArgumentException if bag is null */ protected SynchronizedSortedBag(SortedBag bag) { super(bag); } /** * Constructor that wraps (not copies). * * @param bag the bag to decorate, must not be null * @param lock the lock to use, must not be null * @throws IllegalArgumentException if bag is null */ protected SynchronizedSortedBag(Bag bag, Object lock) { super(bag, lock); } /** * Gets the bag being decorated. * * @return the decorated bag */ protected SortedBag getSortedBag() { return (SortedBag) collection; } //----------------------------------------------------------------------- public synchronized E first() { synchronized (lock) { return getSortedBag().first(); } } public synchronized E last() { synchronized (lock) { return getSortedBag().last(); } } public synchronized Comparator comparator() { synchronized (lock) { return getSortedBag().comparator(); } } } collections-generic-4.01/src/java/org/apache/commons/collections15/bag/SynchronizedBag.java0000644000175000017500000000743510464140763032156 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.bag; import org.apache.commons.collections15.Bag; import org.apache.commons.collections15.collection.SynchronizedCollection; import org.apache.commons.collections15.set.SynchronizedSet; import java.util.Set; /** * Decorates another Bag to synchronize its behaviour * for a multi-threaded environment. *

      * Methods are synchronized, then forwarded to the decorated bag. * Iterators must be separately synchronized around the loop. *

      * This class is Serializable from Commons Collections 3.1. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:19 $ * @since Commons Collections 3.0 */ public class SynchronizedBag extends SynchronizedCollection implements Bag { /** * Serialization version */ private static final long serialVersionUID = 8084674570753837109L; /** * Factory method to create a synchronized bag. * * @param bag the bag to decorate, must not be null * @return a new synchronized Bag * @throws IllegalArgumentException if bag is null */ public static Bag decorate(Bag bag) { return new SynchronizedBag(bag); } //----------------------------------------------------------------------- /** * Constructor that wraps (not copies). * * @param bag the bag to decorate, must not be null * @throws IllegalArgumentException if bag is null */ protected SynchronizedBag(Bag bag) { super(bag); } /** * Constructor that wraps (not copies). * * @param bag the bag to decorate, must not be null * @param lock the lock to use, must not be null * @throws IllegalArgumentException if bag is null */ protected SynchronizedBag(Bag bag, Object lock) { super(bag, lock); } /** * Gets the bag being decorated. * * @return the decorated bag */ protected Bag getBag() { return (Bag) collection; } //----------------------------------------------------------------------- public boolean add(E object, int count) { synchronized (lock) { return getBag().add(object, count); } } public boolean remove(E object, int count) { synchronized (lock) { return getBag().remove(object, count); } } public Set uniqueSet() { synchronized (lock) { Set set = getBag().uniqueSet(); return new SynchronizedBagSet(set, lock); } } public int getCount(E object) { synchronized (lock) { return getBag().getCount(object); } } //----------------------------------------------------------------------- /** * Synchronized Set for the Bag class. */ class SynchronizedBagSet extends SynchronizedSet { /** * Constructor. * * @param set the set to decorate * @param lock the lock to use, shared with the bag */ SynchronizedBagSet(Set set, Object lock) { super(set, lock); } } } collections-generic-4.01/src/java/org/apache/commons/collections15/bag/TypedSortedBag.java0000644000175000017500000000412410464140763031735 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.bag; import org.apache.commons.collections15.SortedBag; import org.apache.commons.collections15.functors.InstanceofPredicate; /** * Decorates another SortedBag to validate that elements added * are of a specific type. *

      * The validation of additions is performed via an instanceof test against * a specified Class. If an object cannot be added to the * collection, an IllegalArgumentException is thrown. * * @author Stephen Colebourne * @author Matt Hall, John Watkinson, Matthew Hawthorne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:19 $ * @since Commons Collections 3.0 */ public class TypedSortedBag { /** * Factory method to create a typed sorted bag. *

      * If there are any elements already in the bag being decorated, they * are validated. * * @param bag the bag to decorate, must not be null * @param type the type to allow into the bag, must not be null * @return a new transformed SortedBag * @throws IllegalArgumentException if bag or type is null * @throws IllegalArgumentException if the bag contains invalid elements */ public static SortedBag decorate(SortedBag bag, Class type) { return new PredicatedSortedBag(bag, InstanceofPredicate.getInstance(type)); } /** * Restrictive constructor. */ protected TypedSortedBag() { super(); } } collections-generic-4.01/src/java/org/apache/commons/collections15/bag/TreeBag.java0000644000175000017500000000732410464140764030374 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2002-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.bag; import org.apache.commons.collections15.SortedBag; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.Collection; import java.util.Comparator; import java.util.SortedMap; import java.util.TreeMap; /** * Implements SortedBag, using a TreeMap to provide * the data storage. This is the standard implementation of a sorted bag. *

      * Order will be maintained among the bag members and can be viewed through the * iterator. *

      * A Bag stores each object in the collection together with a * count of occurrences. Extra methods on the interface allow multiple copies * of an object to be added or removed at once. It is important to read the * interface javadoc carefully as several methods violate the * Collection interface specification. * * @author Matt Hall, John Watkinson, Chuck Burdick * @author Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:19 $ * @since Commons Collections 3.0 (previously in main package v2.0) */ public class TreeBag extends AbstractMapBag implements SortedBag, Serializable { /** * Serial version lock */ static final long serialVersionUID = -7740146511091606676L; /** * Constructs an empty TreeBag. */ public TreeBag() { super(new TreeMap()); } /** * Constructs an empty bag that maintains order on its unique * representative members according to the given {@link Comparator}. * * @param comparator the comparator to use */ public TreeBag(Comparator comparator) { super(new TreeMap(comparator)); } /** * Constructs a TreeBag containing all the members of the * specified collection. * * @param coll the collection to copy into the bag */ public TreeBag(Collection coll) { this(); addAll(coll); } //----------------------------------------------------------------------- public E first() { return ((SortedMap) getMap()).firstKey(); } public E last() { return ((SortedMap) getMap()).lastKey(); } public Comparator comparator() { return ((SortedMap) getMap()).comparator(); } //----------------------------------------------------------------------- /** * Write the bag out using a custom routine. */ private void writeObject(ObjectOutputStream out) throws IOException { out.defaultWriteObject(); out.writeObject(comparator()); super.doWriteObject(out); } /** * Read the bag in using a custom routine. */ private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); Comparator comp = (Comparator) in.readObject(); super.doReadObject(new TreeMap(comp), in); } } collections-generic-4.01/src/java/org/apache/commons/collections15/bag/AbstractBagDecorator.java0000644000175000017500000000441710464140763033102 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.bag; import org.apache.commons.collections15.Bag; import org.apache.commons.collections15.collection.AbstractCollectionDecorator; import java.util.Set; /** * Decorates another Bag to provide additional behaviour. *

      * Methods are forwarded directly to the decorated bag. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:19 $ * @since Commons Collections 3.0 */ public abstract class AbstractBagDecorator extends AbstractCollectionDecorator implements Bag { /** * Constructor only used in deserialization, do not use otherwise. * * @since Commons Collections 3.1 */ protected AbstractBagDecorator() { super(); } /** * Constructor that wraps (not copies). * * @param bag the bag to decorate, must not be null * @throws IllegalArgumentException if list is null */ protected AbstractBagDecorator(Bag bag) { super(bag); } /** * Gets the bag being decorated. * * @return the decorated bag */ protected Bag getBag() { return (Bag) getCollection(); } //----------------------------------------------------------------------- public int getCount(E object) { return getBag().getCount(object); } public boolean add(E object, int count) { return getBag().add(object, count); } public boolean remove(E object, int count) { return getBag().remove(object, count); } public Set uniqueSet() { return getBag().uniqueSet(); } } collections-generic-4.01/src/java/org/apache/commons/collections15/bag/TypedBag.java0000644000175000017500000000422110464140754030552 0ustar giovannigiovanni// GenericsNote: Deprecated and not coverted, type safety not necessary anymore. /* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.bag; import org.apache.commons.collections15.Bag; import org.apache.commons.collections15.functors.InstanceofPredicate; /** * Decorates another Bag to validate that elements added * are of a specific type. *

      * The validation of additions is performed via an instanceof test against * a specified Class. If an object cannot be added to the * collection, an IllegalArgumentException is thrown. * * @author Stephen Colebourne * @author Matt Hall, John Watkinson, Matthew Hawthorne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:19 $ * @since Commons Collections 3.0 * @deprecated Type safety classes not required anymore under 1.5, just use a typed Bag. */ public class TypedBag { /** * Factory method to create a typed bag. *

      * If there are any elements already in the bag being decorated, they * are validated. * * @param bag the bag to decorate, must not be null * @param type the type to allow into the bag, must not be null * @return a new typed Bag * @throws IllegalArgumentException if bag or type is null * @throws IllegalArgumentException if the bag contains invalid elements */ public static Bag decorate(Bag bag, Class type) { return new PredicatedBag(bag, InstanceofPredicate.getInstance(type)); } /** * Restrictive constructor. */ protected TypedBag() { super(); } } collections-generic-4.01/src/java/org/apache/commons/collections15/bag/TransformedSortedBag.java0000644000175000017500000000655110464140754033142 0ustar giovannigiovanni// TODO: Not yet converted - deprecated (by me). /* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.bag; import org.apache.commons.collections15.SortedBag; import org.apache.commons.collections15.Transformer; import java.util.Comparator; /** * Decorates another SortedBag to transform objects that are added. *

      * The add methods are affected by this class. * Thus objects must be removed or searched for using their transformed form. * For example, if the transformation converts Strings to Integers, you must * use the Integer form to remove objects. *

      * This class is Serializable from Commons Collections 3.1. *

      * Note: This class cannot support generics without breaking the Collection contract. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:19 $ * @since Commons Collections 3.0 */ public class TransformedSortedBag extends TransformedBag implements SortedBag { /** * Serialization version */ private static final long serialVersionUID = -251737742649401930L; /** * Factory method to create a transforming sorted bag. *

      * If there are any elements already in the bag being decorated, they * are NOT transformed. * * @param bag the bag to decorate, must not be null * @param transformer the transformer to use for conversion, must not be null * @return a new transformed SortedBag * @throws IllegalArgumentException if bag or transformer is null */ public static SortedBag decorate(SortedBag bag, Transformer transformer) { return new TransformedSortedBag(bag, transformer); } //----------------------------------------------------------------------- /** * Constructor that wraps (not copies). *

      * If there are any elements already in the bag being decorated, they * are NOT transformed. * * @param bag the bag to decorate, must not be null * @param transformer the transformer to use for conversion, must not be null * @throws IllegalArgumentException if bag or transformer is null */ protected TransformedSortedBag(SortedBag bag, Transformer transformer) { super(bag, transformer); } /** * Gets the decorated bag. * * @return the decorated bag */ protected SortedBag getSortedBag() { return (SortedBag) collection; } //----------------------------------------------------------------------- public Object first() { return getSortedBag().first(); } public Object last() { return getSortedBag().last(); } public Comparator comparator() { return getSortedBag().comparator(); } } collections-generic-4.01/src/java/org/apache/commons/collections15/bag/AbstractMapBag.java0000644000175000017500000004306610464140761031676 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2002-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.bag; import org.apache.commons.collections15.Bag; import org.apache.commons.collections15.set.UnmodifiableSet; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.lang.reflect.Array; import java.util.*; /** * Abstract implementation of the {@link Bag} interface to simplify the creation * of subclass implementations. *

      * Subclasses specify a Map implementation to use as the internal storage. * The map will be used to map bag elements to a number; the number represents * the number of occurrences of that element in the bag. * * @author Chuck Burdick * @author Michael A. Smith * @author Stephen Colebourne * @author Matt Hall, John Watkinson, Janek Bogucki * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:19 $ * @since Commons Collections 3.0 (previously DefaultMapBag v2.0) */ public abstract class AbstractMapBag implements Bag { /** * The map to use to store the data */ private transient Map map; /** * The current total size of the bag */ private int size; /** * The modification count for fail fast iterators */ private transient int modCount; /** * The modification count for fail fast iterators */ private transient Set uniqueSet; /** * Constructor needed for subclass serialisation. */ protected AbstractMapBag() { super(); } /** * Constructor that assigns the specified Map as the backing store. * The map must be empty and non-null. * * @param map the map to assign */ protected AbstractMapBag(Map map) { super(); this.map = map; } /** * Utility method for implementations to access the map that backs * this bag. Not intended for interactive use outside of subclasses. * * @return the map being used by the Bag */ protected Map getMap() { return map; } //----------------------------------------------------------------------- /** * Returns the number of elements in this bag. * * @return current size of the bag */ public int size() { return size; } /** * Returns true if the underlying map is empty. * * @return true if bag is empty */ public boolean isEmpty() { return map.isEmpty(); } /** * Returns the number of occurrence of the given element in this bag * by looking up its count in the underlying map. * * @param object the object to search for * @return the number of occurrences of the object, zero if not found */ public int getCount(E object) { MutableInteger count = map.get(object); if (count != null) { return count.value; } return 0; } //----------------------------------------------------------------------- /** * Determines if the bag contains the given element by checking if the * underlying map contains the element as a key. * * @param object the object to search for * @return true if the bag contains the given element */ public boolean contains(Object object) { return map.containsKey(object); } /** * Determines if the bag contains the given elements. * * @param coll the collection to check against * @return true if the Bag contains all the collection */ public boolean containsAll(Collection coll) { if (coll instanceof Bag) { return containsAll((Bag) coll); } return containsAll(new HashBag(coll)); } /** * Returns true if the bag contains all elements in * the given collection, respecting cardinality. * * @param other the bag to check against * @return true if the Bag contains all the collection */ boolean containsAll(Bag other) { boolean result = true; Iterator it = other.uniqueSet().iterator(); while (it.hasNext()) { E current = it.next(); boolean contains = getCount(current) >= other.getCount(current); result = result && contains; } return result; } //----------------------------------------------------------------------- /** * Gets an iterator over the bag elements. * Elements present in the Bag more than once will be returned repeatedly. * * @return the iterator */ public Iterator iterator() { return new BagIterator(this); } /** * Inner class iterator for the Bag. */ static class BagIterator implements Iterator { private AbstractMapBag parent; private Iterator> entryIterator; private Map.Entry current; private int itemCount; private final int mods; private boolean canRemove; /** * Constructor. * * @param parent the parent bag */ public BagIterator(AbstractMapBag parent) { this.parent = parent; this.entryIterator = parent.map.entrySet().iterator(); this.current = null; this.mods = parent.modCount; this.canRemove = false; } public boolean hasNext() { return (itemCount > 0 || entryIterator.hasNext()); } public E next() { if (parent.modCount != mods) { throw new ConcurrentModificationException(); } if (itemCount == 0) { current = entryIterator.next(); itemCount = current.getValue().value; } canRemove = true; itemCount--; return current.getKey(); } public void remove() { if (parent.modCount != mods) { throw new ConcurrentModificationException(); } if (canRemove == false) { throw new IllegalStateException(); } MutableInteger mut = current.getValue(); if (mut.value > 0) { mut.value--; parent.size--; } else { entryIterator.remove(); } canRemove = false; } } //----------------------------------------------------------------------- /** * Adds a new element to the bag, incrementing its count in the underlying map. * * @param object the object to add * @return true if the object was not already in the uniqueSet */ public boolean add(E object) { return add(object, 1); } /** * Adds a new element to the bag, incrementing its count in the map. * * @param object the object to search for * @param nCopies the number of copies to add * @return true if the object was not already in the uniqueSet */ public boolean add(E object, int nCopies) { modCount++; if (nCopies > 0) { MutableInteger mut = map.get(object); size += nCopies; if (mut == null) { map.put(object, new MutableInteger(nCopies)); return true; } else { mut.value += nCopies; return false; } } else { return false; } } /** * Invokes {@link #add(Object)} for each element in the given collection. * * @param coll the collection to add * @return true if this call changed the bag */ public boolean addAll(Collection coll) { boolean changed = false; Iterator i = coll.iterator(); while (i.hasNext()) { boolean added = add(i.next()); changed = changed || added; } return changed; } //----------------------------------------------------------------------- /** * Clears the bag by clearing the underlying map. */ public void clear() { modCount++; map.clear(); size = 0; } /** * Removes all copies of the specified object from the bag. * * @param object the object to remove * @return true if the bag changed */ public boolean remove(Object object) { MutableInteger mut = map.get(object); if (mut == null) { return false; } modCount++; map.remove(object); size -= mut.value; return true; } /** * Removes a specified number of copies of an object from the bag. * * @param object the object to remove * @param nCopies the number of copies to remove * @return true if the bag changed */ public boolean remove(E object, int nCopies) { MutableInteger mut = map.get(object); if (mut == null) { return false; } if (nCopies <= 0) { return false; } modCount++; if (nCopies < mut.value) { mut.value -= nCopies; map.put(object, mut); size -= nCopies; } else { map.remove(object); size -= mut.value; } return true; } /** * Removes objects from the bag according to their count in the specified collection. * * @param coll the collection to use * @return true if the bag changed */ public boolean removeAll(Collection coll) { boolean result = false; if (coll != null) { Iterator i = coll.iterator(); while (i.hasNext()) { boolean changed = remove((E) i.next(), 1); result = result || changed; } } return result; } /** * Remove any members of the bag that are not in the given * bag, respecting cardinality. * * @param coll the collection to retain * @return true if this call changed the collection */ public boolean retainAll(Collection coll) { if (coll instanceof Bag) { return retainAll((Bag) coll); } return retainAll(new HashBag(coll)); } /** * Remove any members of the bag that are not in the given * bag, respecting cardinality. * * @param other the bag to retain * @return true if this call changed the collection * @see #retainAll(Collection) */ boolean retainAll(Bag other) { boolean result = false; Bag excess = new HashBag(); Iterator i = uniqueSet().iterator(); while (i.hasNext()) { E current = i.next(); int myCount = getCount(current); int otherCount = other.getCount(current); if (1 <= otherCount && otherCount <= myCount) { excess.add(current, myCount - otherCount); } else { excess.add(current, myCount); } } if (!excess.isEmpty()) { result = removeAll(excess); } return result; } //----------------------------------------------------------------------- /** * Mutable integer class for storing the data. */ protected static class MutableInteger { /** * The value of this mutable. */ protected int value; /** * Constructor. * * @param value the initial value */ MutableInteger(int value) { this.value = value; } public boolean equals(Object obj) { if (obj instanceof MutableInteger == false) { return false; } return ((MutableInteger) obj).value == value; } public int hashCode() { return value; } } /** * Returns an array of all of this bag's elements. * * @return an array of all of this bag's elements */ public Object[] toArray() { Object[] result = new Object[size()]; int i = 0; Iterator it = map.keySet().iterator(); while (it.hasNext()) { E current = it.next(); for (int index = getCount(current); index > 0; index--) { result[i++] = current; } } return result; } /** * Returns an array of all of this bag's elements. * * @param array the array to populate * @return an array of all of this bag's elements */ public Object[] toArray(Object[] array) { int size = size(); if (array.length < size) { array = (Object[]) Array.newInstance(array.getClass().getComponentType(), size); } int i = 0; Iterator it = map.keySet().iterator(); while (it.hasNext()) { E current = it.next(); for (int index = getCount(current); index > 0; index--) { array[i++] = current; } } if (array.length > size) { array[size] = null; } return array; } /** * Returns an unmodifiable view of the underlying map's key set. * * @return the set of unique elements in this bag */ public Set uniqueSet() { if (uniqueSet == null) { uniqueSet = UnmodifiableSet.decorate(map.keySet()); } return uniqueSet; } //----------------------------------------------------------------------- /** * Write the map out using a custom routine. * * @param out the output stream * @throws IOException */ protected void doWriteObject(ObjectOutputStream out) throws IOException { out.writeInt(map.size()); for (Iterator> it = map.entrySet().iterator(); it.hasNext();) { Map.Entry entry = it.next(); out.writeObject(entry.getKey()); out.writeInt(entry.getValue().value); } } /** * Read the map in using a custom routine. * * @param map the map to use * @param in the input stream * @throws IOException * @throws ClassNotFoundException */ protected void doReadObject(Map map, ObjectInputStream in) throws IOException, ClassNotFoundException { this.map = map; int entrySize = in.readInt(); for (int i = 0; i < entrySize; i++) { E obj = (E) in.readObject(); int count = in.readInt(); map.put(obj, new MutableInteger(count)); size += count; } } //----------------------------------------------------------------------- /** * Compares this Bag to another. * This Bag equals another Bag if it contains the same number of occurrences of * the same elements. * * @param object the Bag to compare to * @return true if equal */ public boolean equals(Object object) { if (object == this) { return true; } if (object instanceof Bag == false) { return false; } Bag other = (Bag) object; if (other.size() != size()) { return false; } for (Iterator it = map.keySet().iterator(); it.hasNext();) { E element = it.next(); if (other.getCount(element) != getCount(element)) { return false; } } return true; } /** * Gets a hash code for the Bag compatible with the definition of equals. * The hash code is defined as the sum total of a hash code for each element. * The per element hash code is defined as * (e==null ? 0 : e.hashCode()) ^ noOccurances). * This hash code is compatible with the Set interface. * * @return the hash code of the Bag */ public int hashCode() { int total = 0; for (Iterator> it = map.entrySet().iterator(); it.hasNext();) { Map.Entry entry = it.next(); Object element = entry.getKey(); Integer count = entry.getValue().value; total += (element == null ? 0 : element.hashCode()) ^ count; } return total; } /** * Implement a toString() method suitable for debugging. * * @return a debugging toString */ public String toString() { if (size() == 0) { return "[]"; } StringBuffer buf = new StringBuffer(); buf.append('['); Iterator it = uniqueSet().iterator(); while (it.hasNext()) { E current = it.next(); int count = getCount(current); buf.append(count); buf.append(':'); buf.append(current); if (it.hasNext()) { buf.append(','); } } buf.append(']'); return buf.toString(); } } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootcollections-generic-4.01/src/java/org/apache/commons/collections15/bag/AbstractSortedBagDecorator.javacollections-generic-4.01/src/java/org/apache/commons/collections15/bag/AbstractSortedBagDecorator.ja0000644000175000017500000000417510464140755033736 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.bag; import org.apache.commons.collections15.SortedBag; import java.util.Comparator; /** * Decorates another SortedBag to provide additional behaviour. *

      * Methods are forwarded directly to the decorated bag. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:19 $ * @since Commons Collections 3.0 */ public abstract class AbstractSortedBagDecorator extends AbstractBagDecorator implements SortedBag { /** * Constructor only used in deserialization, do not use otherwise. * * @since Commons Collections 3.1 */ protected AbstractSortedBagDecorator() { super(); } /** * Constructor that wraps (not copies). * * @param bag the bag to decorate, must not be null * @throws IllegalArgumentException if list is null */ protected AbstractSortedBagDecorator(SortedBag bag) { super(bag); } /** * Gets the bag being decorated. * * @return the decorated bag */ protected SortedBag getSortedBag() { return (SortedBag) getCollection(); } //----------------------------------------------------------------------- public E first() { return getSortedBag().first(); } public E last() { return getSortedBag().last(); } public Comparator comparator() { return getSortedBag().comparator(); } } collections-generic-4.01/src/java/org/apache/commons/collections15/bag/PredicatedBag.java0000644000175000017500000000726610464140756031547 0ustar giovannigiovanni// GenericsNotes: Converted. /* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.bag; import org.apache.commons.collections15.Bag; import org.apache.commons.collections15.Predicate; import org.apache.commons.collections15.collection.PredicatedCollection; import java.util.Set; /** * Decorates another Bag to validate that additions * match a specified predicate. *

      * This bag exists to provide validation for the decorated bag. * It is normally created to decorate an empty bag. * If an object cannot be added to the bag, an IllegalArgumentException is thrown. *

      * One usage would be to ensure that no null entries are added to the bag. *

      Bag bag = PredicatedBag.decorate(new HashBag(), NotNullPredicate.INSTANCE);
      *

      * This class is Serializable from Commons Collections 3.1. * * @author Stephen Colebourne * @author Matt Hall, John Watkinson, Paul Jack * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:19 $ * @since Commons Collections 3.0 */ public class PredicatedBag extends PredicatedCollection implements Bag { /** * Serialization version */ private static final long serialVersionUID = -2575833140344736876L; /** * Factory method to create a predicated (validating) bag. *

      * If there are any elements already in the bag being decorated, they * are validated. * * @param bag the bag to decorate, must not be null * @param predicate the predicate to use for validation, must not be null * @return a new predicated Bag * @throws IllegalArgumentException if bag or predicate is null * @throws IllegalArgumentException if the bag contains invalid elements */ public static Bag decorate(Bag bag, Predicate predicate) { return new PredicatedBag(bag, predicate); } //----------------------------------------------------------------------- /** * Constructor that wraps (not copies). *

      * If there are any elements already in the bag being decorated, they * are validated. * * @param bag the bag to decorate, must not be null * @param predicate the predicate to use for validation, must not be null * @throws IllegalArgumentException if bag or predicate is null * @throws IllegalArgumentException if the bag contains invalid elements */ protected PredicatedBag(Bag bag, Predicate predicate) { super(bag, predicate); } /** * Gets the decorated bag. * * @return the decorated bag */ protected Bag getBag() { return (Bag) getCollection(); } //----------------------------------------------------------------------- public boolean add(E object, int count) { validate(object); return getBag().add(object, count); } public boolean remove(E object, int count) { return getBag().remove(object, count); } public Set uniqueSet() { return getBag().uniqueSet(); } public int getCount(E object) { return getBag().getCount(object); } } collections-generic-4.01/src/java/org/apache/commons/collections15/bag/HashBag.java0000644000175000017500000000534110464140754030354 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2002-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.bag; import org.apache.commons.collections15.Bag; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.Collection; import java.util.HashMap; /** * Implements Bag, using a HashMap to provide the * data storage. This is the standard implementation of a bag. *

      * A Bag stores each object in the collection together with a * count of occurrences. Extra methods on the interface allow multiple copies * of an object to be added or removed at once. It is important to read the * interface javadoc carefully as several methods violate the * Collection interface specification. * * @author Chuck Burdick * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:19 $ * @since Commons Collections 3.0 (previously in main package v2.0) */ public class HashBag extends AbstractMapBag implements Bag, Serializable { /** * Serial version lock */ static final long serialVersionUID = -6561115435802554013L; /** * Constructs an empty HashBag. */ public HashBag() { super(new HashMap()); } /** * Constructs a bag containing all the members of the given collection. * * @param coll a collection to copy into this bag */ public HashBag(Collection coll) { this(); addAll(coll); } //----------------------------------------------------------------------- /** * Write the bag out using a custom routine. */ private void writeObject(ObjectOutputStream out) throws IOException { out.defaultWriteObject(); super.doWriteObject(out); } /** * Read the bag in using a custom routine. */ private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); super.doReadObject(new HashMap(), in); } } collections-generic-4.01/src/java/org/apache/commons/collections15/bag/package.html0000644000175000017500000000310110464140760030462 0ustar giovannigiovanni

      This package contains implementations of the {@link org.apache.commons.collections.Bag Bag} and {@link org.apache.commons.collections.SortedBag SortedBag} interfaces. A bag stores an object and a count of the number of occurences of the object.

      The following implementations are provided in the package:

      • HashBag - implementation that uses a HashMap to store the data
      • TreeBag - implementation that uses a TreeMap to store the data

      The following decorators are provided in the package:

      • Synchronized - synchronizes method access for multi-threaded environments
      • Unmodifiable - ensures the bag cannot be altered
      • Predicated - ensures that only elements that are valid according to a predicate can be added
      • Typed - ensures that only elements that are of a specific type can be added
      • Transformed - transforms each element added to the bag
      collections-generic-4.01/src/java/org/apache/commons/collections15/bag/UnmodifiableSortedBag.java0000644000175000017500000001062010464140761033242 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.bag; import org.apache.commons.collections15.SortedBag; import org.apache.commons.collections15.Unmodifiable; import org.apache.commons.collections15.iterators.UnmodifiableIterator; import org.apache.commons.collections15.set.UnmodifiableSet; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.Collection; import java.util.Iterator; import java.util.Set; /** * Decorates another SortedBag to ensure it can't be altered. *

      * This class is Serializable from Commons Collections 3.1. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:19 $ * @since Commons Collections 3.0 */ public final class UnmodifiableSortedBag extends AbstractSortedBagDecorator implements Unmodifiable, Serializable { /** * Serialization version */ private static final long serialVersionUID = -3190437252665717841L; /** * Factory method to create an unmodifiable bag. *

      * If the bag passed in is already unmodifiable, it is returned. * * @param bag the bag to decorate, must not be null * @return an unmodifiable SortedBag * @throws IllegalArgumentException if bag is null */ public static SortedBag decorate(SortedBag bag) { if (bag instanceof Unmodifiable) { return bag; } return new UnmodifiableSortedBag(bag); } //----------------------------------------------------------------------- /** * Constructor that wraps (not copies). * * @param bag the bag to decorate, must not be null * @throws IllegalArgumentException if bag is null */ private UnmodifiableSortedBag(SortedBag bag) { super(bag); } //----------------------------------------------------------------------- /** * Write the collection out using a custom routine. * * @param out the output stream * @throws IOException */ private void writeObject(ObjectOutputStream out) throws IOException { out.defaultWriteObject(); out.writeObject(collection); } /** * Read the collection in using a custom routine. * * @param in the input stream * @throws IOException * @throws ClassNotFoundException */ private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); collection = (Collection) in.readObject(); } //----------------------------------------------------------------------- public Iterator iterator() { return UnmodifiableIterator.decorate(getCollection().iterator()); } public boolean add(E object) { throw new UnsupportedOperationException(); } public boolean addAll(Collection coll) { throw new UnsupportedOperationException(); } public void clear() { throw new UnsupportedOperationException(); } public boolean remove(Object object) { throw new UnsupportedOperationException(); } public boolean removeAll(Collection coll) { throw new UnsupportedOperationException(); } public boolean retainAll(Collection coll) { throw new UnsupportedOperationException(); } //----------------------------------------------------------------------- public boolean add(E object, int count) { throw new UnsupportedOperationException(); } public boolean remove(E object, int count) { throw new UnsupportedOperationException(); } public Set uniqueSet() { Set set = getBag().uniqueSet(); return UnmodifiableSet.decorate(set); } } collections-generic-4.01/src/java/org/apache/commons/collections15/bag/UnmodifiableBag.java0000644000175000017500000001052710464140763032071 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.bag; import org.apache.commons.collections15.Bag; import org.apache.commons.collections15.Unmodifiable; import org.apache.commons.collections15.iterators.UnmodifiableIterator; import org.apache.commons.collections15.set.UnmodifiableSet; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.Collection; import java.util.Iterator; import java.util.Set; /** * Decorates another Bag to ensure it can't be altered. *

      * This class is Serializable from Commons Collections 3.1. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:19 $ * @since Commons Collections 3.0 */ public final class UnmodifiableBag extends AbstractBagDecorator implements Unmodifiable, Serializable { /** * Serialization version */ private static final long serialVersionUID = -1873799975157099624L; /** * Factory method to create an unmodifiable bag. *

      * If the bag passed in is already unmodifiable, it is returned. * * @param bag the bag to decorate, must not be null * @return an unmodifiable Bag * @throws IllegalArgumentException if bag is null */ public static Bag decorate(Bag bag) { if (bag instanceof Unmodifiable) { return bag; } return new UnmodifiableBag(bag); } //----------------------------------------------------------------------- /** * Constructor that wraps (not copies). * * @param bag the bag to decorate, must not be null * @throws IllegalArgumentException if bag is null */ private UnmodifiableBag(Bag bag) { super(bag); } //----------------------------------------------------------------------- /** * Write the collection out using a custom routine. * * @param out the output stream * @throws IOException */ private void writeObject(ObjectOutputStream out) throws IOException { out.defaultWriteObject(); out.writeObject(collection); } /** * Read the collection in using a custom routine. * * @param in the input stream * @throws IOException * @throws ClassNotFoundException */ private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); collection = (Collection) in.readObject(); } //----------------------------------------------------------------------- public Iterator iterator() { return UnmodifiableIterator.decorate(getCollection().iterator()); } public boolean add(E object) { throw new UnsupportedOperationException(); } public boolean addAll(Collection coll) { throw new UnsupportedOperationException(); } public void clear() { throw new UnsupportedOperationException(); } public boolean remove(Object object) { throw new UnsupportedOperationException(); } public boolean removeAll(Collection coll) { throw new UnsupportedOperationException(); } public boolean retainAll(Collection coll) { throw new UnsupportedOperationException(); } //----------------------------------------------------------------------- public boolean add(E object, int count) { throw new UnsupportedOperationException(); } public boolean remove(E object, int count) { throw new UnsupportedOperationException(); } public Set uniqueSet() { Set set = getBag().uniqueSet(); return UnmodifiableSet.decorate(set); } } collections-generic-4.01/src/java/org/apache/commons/collections15/bag/PredicatedSortedBag.java0000644000175000017500000000706410464140760032717 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.bag; import org.apache.commons.collections15.Predicate; import org.apache.commons.collections15.SortedBag; import java.util.Comparator; /** * Decorates another SortedBag to validate that additions * match a specified predicate. *

      * This bag exists to provide validation for the decorated bag. * It is normally created to decorate an empty bag. * If an object cannot be added to the bag, an IllegalArgumentException is thrown. *

      * One usage would be to ensure that no null entries are added to the bag. *

      SortedBag bag = PredicatedSortedBag.decorate(new TreeBag(), NotNullPredicate.INSTANCE);
      *

      * This class is Serializable from Commons Collections 3.1. * * @author Stephen Colebourne * @author Matt Hall, John Watkinson, Paul Jack * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:19 $ * @since Commons Collections 3.0 */ public class PredicatedSortedBag extends PredicatedBag implements SortedBag { /** * Serialization version */ private static final long serialVersionUID = 3448581314086406616L; /** * Factory method to create a predicated (validating) bag. *

      * If there are any elements already in the bag being decorated, they * are validated. * * @param bag the bag to decorate, must not be null * @param predicate the predicate to use for validation, must not be null * @return a new predicated SortedBag * @throws IllegalArgumentException if bag or predicate is null * @throws IllegalArgumentException if the bag contains invalid elements */ public static SortedBag decorate(SortedBag bag, Predicate predicate) { return new PredicatedSortedBag(bag, predicate); } //----------------------------------------------------------------------- /** * Constructor that wraps (not copies). *

      * If there are any elements already in the bag being decorated, they * are validated. * * @param bag the bag to decorate, must not be null * @param predicate the predicate to use for validation, must not be null * @throws IllegalArgumentException if bag or predicate is null * @throws IllegalArgumentException if the bag contains invalid elements */ protected PredicatedSortedBag(SortedBag bag, Predicate predicate) { super(bag, predicate); } /** * Gets the decorated sorted bag. * * @return the decorated bag */ protected SortedBag getSortedBag() { return (SortedBag) getCollection(); } //----------------------------------------------------------------------- public E first() { return getSortedBag().first(); } public E last() { return getSortedBag().last(); } public Comparator comparator() { return getSortedBag().comparator(); } } collections-generic-4.01/src/java/org/apache/commons/collections15/BidiMap.java0000644000175000017500000001563310464140765027642 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15; import java.util.Set; /** * Defines a map that allows bidirectional lookup between key and values. *

      * This extended Map represents a mapping where a key may * lookup a value and a value may lookup a key with equal ease. * This interface extends Map and so may be used anywhere a map * is required. The interface provides an inverse map view, enabling * full access to both directions of the BidiMap. *

      * Implementations should allow a value to be looked up from a key and * a key to be looked up from a value with equal performance. *

      * This map enforces the restriction that there is a 1:1 relation between * keys and values, meaning that multiple keys cannot map to the same value. * This is required so that "inverting" the map results in a map without * duplicate keys. See the {@link #put} method description for more information. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:19 $ * @since Commons Collections 3.0 */ public interface BidiMap extends IterableMap { /** * Obtains a MapIterator over the map. *

      * A map iterator is an efficient way of iterating over maps. * It does not require that the map is stored using Map Entry objects * which can increase performance. *

           * BidiMap map = new DualHashBidiMap();
           * MapIterator it = map.mapIterator();
           * while (it.hasNext()) {
           *   Object key = it.next();
           *   Object value = it.getValue();
           *   it.setValue("newValue");
           * }
           * 
      * * @return a map iterator */ MapIterator mapIterator(); /** * Puts the key-value pair into the map, replacing any previous pair. *

      * When adding a key-value pair, the value may already exist in the map * against a different key. That mapping is removed, to ensure that the * value only occurs once in the inverse map. *

           *  BidiMap map1 = new DualHashBidiMap();
           *  map.put("A","B");  // contains A mapped to B, as per Map
           *  map.put("A","C");  // contains A mapped to C, as per Map
           * 

      * BidiMap map2 = new DualHashBidiMap(); * map.put("A","B"); // contains A mapped to B, as per Map * map.put("C","B"); // contains C mapped to B, key A is removed *

      * * @param key the key to store * @param value the value to store * @return the previous value mapped to this key * @throws UnsupportedOperationException if the put method is not supported * @throws ClassCastException (optional) if the map limits the type of the * value and the specified value is inappropriate * @throws IllegalArgumentException (optional) if the map limits the values * in some way and the value was invalid * @throws NullPointerException (optional) if the map limits the values to * non-null and null was specified */ V put(K key, V value); /** * Gets the key that is currently mapped to the specified value. *

      * If the value is not contained in the map, null is returned. *

      * Implementations should seek to make this method perform equally as well * as get(Object). * * @param value the value to find the key for * @return the mapped key, or null if not found * @throws ClassCastException (optional) if the map limits the type of the * value and the specified value is inappropriate * @throws NullPointerException (optional) if the map limits the values to * non-null and null was specified */ K getKey(Object value); /** * Removes the key-value pair that is currently mapped to the specified * value (optional operation). *

      * If the value is not contained in the map, null is returned. *

      * Implementations should seek to make this method perform equally as well * as remove(Object). * * @param value the value to find the key-value pair for * @return the key that was removed, null if nothing removed * @throws ClassCastException (optional) if the map limits the type of the * value and the specified value is inappropriate * @throws NullPointerException (optional) if the map limits the values to * non-null and null was specified * @throws UnsupportedOperationException if this method is not supported * by the implementation */ K removeValue(Object value); /** * Gets a view of this map where the keys and values are reversed. *

      * Changes to one map will be visible in the other and vice versa. * This enables both directions of the map to be accessed as a Map. *

      * Implementations should seek to avoid creating a new object every time this * method is called. See AbstractMap.values() etc. Calling this * method on the inverse map should return the original. * * @return an inverted bidirectional map */ BidiMap inverseBidiMap(); /** * Returns a set view of the values contained in this BidiMap. The * set is backed by the map, so changes to the map are reflected in * the collection, and vice-versa. If the map is modified while an * iteration over the collection is in progress (except through the * iterator's own remove operation), the results of the * iteration are undefined. The collection supports element removal, * which removes the corresponding mapping from the map, via the * Iterator.remove, Set.remove, * removeAll, retainAll and clear operations. * It does not support the add or addAll operations. * * @return a Set view of the values contained in this map. */ Set values(); } collections-generic-4.01/src/java/org/apache/commons/collections15/functors/0000755000175000017500000000000011664401370027320 5ustar giovannigiovannicollections-generic-4.01/src/java/org/apache/commons/collections15/functors/EqualPredicate.java0000644000175000017500000000463410464140765033067 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.functors; import org.apache.commons.collections15.Predicate; import java.io.Serializable; /** * Predicate implementation that returns true if the input is the same object * as the one stored in this predicate by equals. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:24 $ * @since Commons Collections 3.0 */ public final class EqualPredicate implements Predicate, Serializable { /** * Serial version UID */ static final long serialVersionUID = 5633766978029907089L; /** * The value to compare to */ private final T iValue; /** * Factory to create the identity predicate. * * @param object the object to compare to * @return the predicate * @throws IllegalArgumentException if the predicate is null */ public static Predicate getInstance(T object) { if (object == null) { return NullPredicate.INSTANCE; } return new EqualPredicate(object); } /** * Constructor that performs no validation. * Use getInstance if you want that. * * @param object the object to compare to */ public EqualPredicate(T object) { super(); iValue = object; } /** * Evaluates the predicate returning true if the input equals the stored value. * * @param object the input object * @return true if input object equals stored value */ public boolean evaluate(T object) { return (iValue.equals(object)); } /** * Gets the value. * * @return the value * @since Commons Collections 3.1 */ public T getValue() { return iValue; } } collections-generic-4.01/src/java/org/apache/commons/collections15/functors/FactoryTransformer.java0000644000175000017500000000506310464140761034022 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.functors; import org.apache.commons.collections15.Factory; import org.apache.commons.collections15.Transformer; import java.io.Serializable; /** * Transformer implementation that calls a Factory and returns the result. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:24 $ * @since Commons Collections 3.0 */ public class FactoryTransformer implements Transformer, Serializable { /** * Serial version UID */ static final long serialVersionUID = -6817674502475353160L; /** * The factory to wrap */ private final Factory iFactory; /** * Factory method that performs validation. * * @param factory the factory to call, not null * @return the factory transformer * @throws IllegalArgumentException if the factory is null */ public static Transformer getInstance(Factory factory) { if (factory == null) { throw new IllegalArgumentException("Factory must not be null"); } return new FactoryTransformer(factory); } /** * Constructor that performs no validation. * Use getInstance if you want that. * * @param factory the factory to call, not null */ public FactoryTransformer(Factory factory) { super(); iFactory = factory; } /** * Transforms the input by ignoring the input and returning the result of * calling the decorated factory. * * @param input the input object to transform * @return the transformed result */ public T transform(I input) { return iFactory.create(); } /** * Gets the factory. * * @return the factory * @since Commons Collections 3.1 */ public Factory getFactory() { return iFactory; } } collections-generic-4.01/src/java/org/apache/commons/collections15/functors/FalsePredicate.java0000644000175000017500000000350310464140762033041 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.functors; import org.apache.commons.collections15.Predicate; import java.io.Serializable; /** * Predicate implementation that always returns false. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:24 $ * @since Commons Collections 3.0 */ public final class FalsePredicate implements Predicate, Serializable { /** * Serial version UID */ static final long serialVersionUID = 7533784454832764388L; /** * Singleton predicate instance */ public static final Predicate INSTANCE = new FalsePredicate(); /** * Factory returning the singleton instance. * * @return the singleton instance * @since Commons Collections 3.1 */ public static Predicate getInstance() { return INSTANCE; } /** * Restricted constructor. */ private FalsePredicate() { super(); } /** * Evaluates the predicate returning false always. * * @param object the input object * @return false always */ public boolean evaluate(T object) { return false; } } collections-generic-4.01/src/java/org/apache/commons/collections15/functors/CloneTransformer.java0000644000175000017500000000407210464140757033457 0ustar giovannigiovanni// GenericsNote: Converted (nothing to convert). /* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.functors; import org.apache.commons.collections15.Transformer; import java.io.Serializable; /** * Transformer implementation that returns a clone of the input object. *

      * Clone is performed using PrototypeFactory.getInstance(input).create(). * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:24 $ * @since Commons Collections 3.0 */ public class CloneTransformer implements Transformer, Serializable { /** * Serial version UID */ static final long serialVersionUID = -8188742709499652567L; /** * Singleton predicate instance */ public static final Transformer INSTANCE = new CloneTransformer(); /** * Factory returning the singleton instance. * * @return the singleton instance * @since Commons Collections 3.1 */ public static Transformer getInstance() { return INSTANCE; } /** * Constructor */ private CloneTransformer() { super(); } /** * Transforms the input to result by cloning it. * * @param input the input object to transform * @return the transformed result */ public T transform(T input) { if (input == null) { return null; } return PrototypeFactory.getInstance(input).create(); } } collections-generic-4.01/src/java/org/apache/commons/collections15/functors/AnyPredicate.java0000644000175000017500000000705410464140756032546 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.functors; import org.apache.commons.collections15.Predicate; import java.io.Serializable; import java.util.Collection; /** * Predicate implementation that returns true if any of the predicates return true. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:24 $ * @since Commons Collections 3.0 */ public final class AnyPredicate implements Predicate, PredicateDecorator, Serializable { /** * Serial version UID */ static final long serialVersionUID = 7429999530934647542L; /** * The array of predicates to call */ private final Predicate[] iPredicates; /** * Factory to create the predicate. * * @param predicates the predicates to check, cloned, not null * @return the any predicate * @throws IllegalArgumentException if the predicates array is null * @throws IllegalArgumentException if the predicates array has less than 2 elements * @throws IllegalArgumentException if any predicate in the array is null */ public static Predicate getInstance(Predicate[] predicates) { FunctorUtils.validateMin2(predicates); predicates = FunctorUtils.copy(predicates); return new AnyPredicate(predicates); } /** * Factory to create the predicate. * * @param predicates the predicates to check, cloned, not null * @return the all predicate * @throws IllegalArgumentException if the predicates array is null * @throws IllegalArgumentException if any predicate in the array is null * @throws IllegalArgumentException if the predicates array has less than 2 elements */ public static Predicate getInstance(Collection> predicates) { Predicate[] preds = FunctorUtils.validate(predicates); return new AnyPredicate(preds); } /** * Constructor that performs no validation. * Use getInstance if you want that. * * @param predicates the predicates to check, not cloned, not null */ public AnyPredicate(Predicate[] predicates) { super(); iPredicates = predicates; } /** * Evaluates the predicate returning true if any predicate returns true. * * @param object the input object * @return true if any decorated predicate return true */ public boolean evaluate(T object) { for (int i = 0; i < iPredicates.length; i++) { if (iPredicates[i].evaluate(object)) { return true; } } return false; } /** * Gets the predicates, do not modify the array. * * @return the predicates * @since Commons Collections 3.1 */ public Predicate[] getPredicates() { return iPredicates; } } collections-generic-4.01/src/java/org/apache/commons/collections15/functors/SwitchTransformer.java0000644000175000017500000001641410464140764033661 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.functors; import org.apache.commons.collections15.Predicate; import org.apache.commons.collections15.Transformer; import java.io.Serializable; import java.util.Iterator; import java.util.Map; /** * Transformer implementation calls the transformer whose predicate returns true, * like a switch statement. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:24 $ * @since Commons Collections 3.0 */ public class SwitchTransformer implements Transformer, Serializable { /** * Serial version UID */ static final long serialVersionUID = -6404460890903469332L; /** * The tests to consider */ private final Predicate[] iPredicates; /** * The matching transformers to call */ private final Transformer[] iTransformers; /** * The default transformer to call if no tests match */ private final Transformer iDefault; /** * Factory method that performs validation and copies the parameter arrays. * * @param predicates array of predicates, cloned, no nulls * @param transformers matching array of transformers, cloned, no nulls * @param defaultTransformer the transformer to use if no match, null means nop * @return the chained transformer * @throws IllegalArgumentException if array is null * @throws IllegalArgumentException if any element in the array is null */ public static Transformer getInstance(Predicate[] predicates, Transformer[] transformers, Transformer defaultTransformer) { FunctorUtils.validate(predicates); FunctorUtils.validate(transformers); if (predicates.length != transformers.length) { throw new IllegalArgumentException("The predicate and transformer arrays must be the same size"); } if (predicates.length == 0) { return (defaultTransformer == null ? ConstantTransformer.NULL_INSTANCE : defaultTransformer); } predicates = FunctorUtils.copy(predicates); transformers = FunctorUtils.copy(transformers); return new SwitchTransformer(predicates, transformers, defaultTransformer); } /** * Create a new Transformer that calls one of the transformers depending * on the predicates. *

      * The Map consists of Predicate keys and Transformer values. A transformer * is called if its matching predicate returns true. Each predicate is evaluated * until one returns true. If no predicates evaluate to true, the default * transformer is called. The default transformer is set in the map with a * null key. The ordering is that of the iterator() method on the entryset * collection of the map. * * @param predicatesAndTransformers a map of predicates to transformers * @return the switch transformer * @throws IllegalArgumentException if the map is null * @throws IllegalArgumentException if any transformer in the map is null * @throws ClassCastException if the map elements are of the wrong type */ public static Transformer getInstance(Map, Transformer> predicatesAndTransformers) { Transformer[] transformers = null; Predicate[] preds = null; if (predicatesAndTransformers == null) { throw new IllegalArgumentException("The predicate and transformer map must not be null"); } if (predicatesAndTransformers.size() == 0) { return ConstantTransformer.NULL_INSTANCE; } // convert to array like this to guarantee iterator() ordering Transformer defaultTransformer = predicatesAndTransformers.remove(null); int size = predicatesAndTransformers.size(); if (size == 0) { return (defaultTransformer == null ? ConstantTransformer.NULL_INSTANCE : defaultTransformer); } transformers = new Transformer[size]; preds = new Predicate[size]; int i = 0; for (Iterator, Transformer>> it = predicatesAndTransformers.entrySet().iterator(); it.hasNext();) { Map.Entry, Transformer> entry = it.next(); preds[i] = entry.getKey(); transformers[i] = entry.getValue(); i++; } return new SwitchTransformer(preds, transformers, defaultTransformer); } /** * Constructor that performs no validation. * Use getInstance if you want that. * * @param predicates array of predicates, not cloned, no nulls * @param transformers matching array of transformers, not cloned, no nulls * @param defaultTransformer the transformer to use if no match, null means nop */ public SwitchTransformer(Predicate[] predicates, Transformer[] transformers, Transformer defaultTransformer) { super(); iPredicates = predicates; iTransformers = transformers; iDefault = (defaultTransformer == null ? ConstantTransformer.NULL_INSTANCE : defaultTransformer); } /** * Transforms the input to result by calling the transformer whose matching * predicate returns true. * * @param input the input object to transform * @return the transformed result */ public O transform(I input) { for (int i = 0; i < iPredicates.length; i++) { if (iPredicates[i].evaluate(input) == true) { return iTransformers[i].transform(input); } } return (O) iDefault.transform(input); } /** * Gets the predicates, do not modify the array. * * @return the predicates * @since Commons Collections 3.1 */ public Predicate[] getPredicates() { return iPredicates; } /** * Gets the transformers, do not modify the array. * * @return the transformers * @since Commons Collections 3.1 */ public Transformer[] getTransformers() { return iTransformers; } /** * Gets the default transformer. * * @return the default transformer * @since Commons Collections 3.1 */ public Transformer getDefaultTransformer() { return iDefault; } } collections-generic-4.01/src/java/org/apache/commons/collections15/functors/InvokerTransformer.java0000644000175000017500000001204410464140764034030 0ustar giovannigiovanni// GenericsNote: Converted (nothing to convert). /* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.functors; import org.apache.commons.collections15.FunctorException; import org.apache.commons.collections15.Transformer; import java.io.Serializable; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; /** * Transformer implementation that creates a new object instance by reflection. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:24 $ * @since Commons Collections 3.0 */ public class InvokerTransformer implements Transformer, Serializable { /** * The serial version */ static final long serialVersionUID = -8653385846894047688L; /** * The method name to call */ private final String iMethodName; /** * The array of reflection parameter types */ private final Class[] iParamTypes; /** * The array of reflection arguments */ private final Object[] iArgs; /** * Gets an instance of this transformer calling a specific method with no arguments. * * @param methodName the method name to call * @return an invoker transformer * @since Commons Collections 3.1 */ public static Transformer getInstance(String methodName) { if (methodName == null) { throw new IllegalArgumentException("The method to invoke must not be null"); } return new InvokerTransformer(methodName); } /** * Gets an instance of this transformer calling a specific method with specific values. * * @param methodName the method name to call * @param paramTypes the parameter types of the method * @param args the arguments to pass to the method * @return an invoker transformer */ public static Transformer getInstance(String methodName, Class[] paramTypes, Object[] args) { if (methodName == null) { throw new IllegalArgumentException("The method to invoke must not be null"); } if (((paramTypes == null) && (args != null)) || ((paramTypes != null) && (args == null)) || ((paramTypes != null) && (args != null) && (paramTypes.length != args.length))) { throw new IllegalArgumentException("The parameter types must match the arguments"); } if (paramTypes == null || paramTypes.length == 0) { return new InvokerTransformer(methodName); } else { paramTypes = (Class[]) paramTypes.clone(); args = (Object[]) args.clone(); return new InvokerTransformer(methodName, paramTypes, args); } } /** * Constructor for no arg instance. * * @param methodName the method to call */ private InvokerTransformer(String methodName) { super(); iMethodName = methodName; iParamTypes = null; iArgs = null; } /** * Constructor that performs no validation. * Use getInstance if you want that. * * @param methodName the method to call * @param paramTypes the constructor parameter types, not cloned * @param args the constructor arguments, not cloned */ public InvokerTransformer(String methodName, Class[] paramTypes, Object[] args) { super(); iMethodName = methodName; iParamTypes = paramTypes; iArgs = args; } /** * Transforms the input to result by invoking a method on the input. * * @param input the input object to transform * @return the transformed result, null if null input */ public Object transform(Object input) { if (input == null) { return null; } try { Class cls = input.getClass(); Method method = cls.getMethod(iMethodName, iParamTypes); return method.invoke(input, iArgs); } catch (NoSuchMethodException ex) { throw new FunctorException("InvokerTransformer: The method '" + iMethodName + "' on '" + input.getClass() + "' does not exist"); } catch (IllegalAccessException ex) { throw new FunctorException("InvokerTransformer: The method '" + iMethodName + "' on '" + input.getClass() + "' cannot be accessed"); } catch (InvocationTargetException ex) { throw new FunctorException("InvokerTransformer: The method '" + iMethodName + "' on '" + input.getClass() + "' threw an exception", ex); } } } collections-generic-4.01/src/java/org/apache/commons/collections15/functors/IdentityPredicate.java0000644000175000017500000000467210464140756033613 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.functors; import org.apache.commons.collections15.Predicate; import java.io.Serializable; /** * Predicate implementation that returns true if the input is the same object * as the one stored in this predicate. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:24 $ * @since Commons Collections 3.0 */ public final class IdentityPredicate implements Predicate, Serializable { /** * Serial version UID */ static final long serialVersionUID = -89901658494523293L; /** * The value to compare to */ private final T iValue; /** * Factory to create the identity predicate. * * @param object the object to compare to * @return the predicate * @throws IllegalArgumentException if the predicate is null */ public static Predicate getInstance(T object) { if (object == null) { return NullPredicate.INSTANCE; } return new IdentityPredicate(object); } /** * Constructor that performs no validation. * Use getInstance if you want that. * * @param object the object to compare to */ public IdentityPredicate(T object) { super(); iValue = object; } /** * Evaluates the predicate returning true if the input object is identical to * the stored object. * * @param object the input object * @return true if input is the same object as the stored value */ public boolean evaluate(T object) { return (iValue == object); } /** * Gets the value. * * @return the value * @since Commons Collections 3.1 */ public T getValue() { return iValue; } } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootcollections-generic-4.01/src/java/org/apache/commons/collections15/functors/NullIsFalsePredicate.javacollections-generic-4.01/src/java/org/apache/commons/collections15/functors/NullIsFalsePredicate.jav0000644000175000017500000000536410464140763034037 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.functors; import org.apache.commons.collections15.Predicate; import java.io.Serializable; /** * Predicate implementation that returns false if the input is null. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:24 $ * @since Commons Collections 3.0 */ public final class NullIsFalsePredicate implements Predicate, PredicateDecorator, Serializable { /** * Serial version UID */ static final long serialVersionUID = -2997501534564735525L; /** * The predicate to decorate */ private final Predicate iPredicate; /** * Factory to create the null false predicate. * * @param predicate the predicate to decorate, not null * @return the predicate * @throws IllegalArgumentException if the predicate is null */ public static Predicate getInstance(Predicate predicate) { if (predicate == null) { throw new IllegalArgumentException("Predicate must not be null"); } return new NullIsFalsePredicate(predicate); } /** * Constructor that performs no validation. * Use getInstance if you want that. * * @param predicate the predicate to call after the null check */ public NullIsFalsePredicate(Predicate predicate) { super(); iPredicate = predicate; } /** * Evaluates the predicate returning the result of the decorated predicate * once a null check is performed. * * @param object the input object * @return true if decorated predicate returns true, false if input is null */ public boolean evaluate(T object) { if (object == null) { return false; } return iPredicate.evaluate(object); } /** * Gets the predicate being decorated. * * @return the predicate as the only element in an array * @since Commons Collections 3.1 */ public Predicate[] getPredicates() { return new Predicate[]{iPredicate}; } } collections-generic-4.01/src/java/org/apache/commons/collections15/functors/NotNullPredicate.java0000644000175000017500000000361110464140763033403 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.functors; import org.apache.commons.collections15.Predicate; import java.io.Serializable; /** * Predicate implementation that returns true if the input is not null. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:24 $ * @since Commons Collections 3.0 */ public final class NotNullPredicate implements Predicate, Serializable { /** * Serial version UID */ static final long serialVersionUID = 7533784454832764388L; /** * Singleton predicate instance */ public static final Predicate INSTANCE = new NotNullPredicate(); /** * Factory returning the singleton instance. * * @return the singleton instance * @since Commons Collections 3.1 */ public static Predicate getInstance() { return INSTANCE; } /** * Restricted constructor. */ private NotNullPredicate() { super(); } /** * Evaluates the predicate returning true if the object does not equal null. * * @param object the object to evaluate * @return true if not null */ public boolean evaluate(T object) { return (object != null); } } ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootcollections-generic-4.01/src/java/org/apache/commons/collections15/functors/StringValueTransformer.javacollections-generic-4.01/src/java/org/apache/commons/collections15/functors/StringValueTransformer.j0000644000175000017500000000353110464140757034171 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.functors; import org.apache.commons.collections15.Transformer; import java.io.Serializable; /** * Transformer implementation that returns the String.valueOf. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:24 $ * @since Commons Collections 3.0 */ public final class StringValueTransformer implements Transformer, Serializable { /** * Serial version UID */ static final long serialVersionUID = 7511110693171758606L; /** * Factory returning the singleton instance. * * @return the singleton instance * @since Commons Collections 3.1 */ public static Transformer getInstance() { return new StringValueTransformer(); } /** * Restricted constructor. */ private StringValueTransformer() { super(); } /** * Transforms the input to result by calling String.valueOf. * * @param input the input object to transform * @return the transformed result */ public String transform(T input) { return String.valueOf(input); } } collections-generic-4.01/src/java/org/apache/commons/collections15/functors/NOPTransformer.java0000644000175000017500000000353110464140755033050 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.functors; import org.apache.commons.collections15.Transformer; import java.io.Serializable; /** * Transformer implementation that does nothing. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:24 $ * @since Commons Collections 3.0 */ public class NOPTransformer implements Transformer, Serializable { /** * Serial version UID */ static final long serialVersionUID = 2133891748318574490L; /** * Singleton predicate instance */ public static final Transformer INSTANCE = new NOPTransformer(); /** * Factory returning the singleton instance. * * @return the singleton instance * @since Commons Collections 3.1 */ public static Transformer getInstance() { return INSTANCE; } /** * Constructor */ private NOPTransformer() { super(); } /** * Transforms the input to result by doing nothing. * * @param input the input object to transform * @return the transformed result which is the input */ public I transform(I input) { return input; } } collections-generic-4.01/src/java/org/apache/commons/collections15/functors/NotPredicate.java0000644000175000017500000000513310464140763032551 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.functors; import org.apache.commons.collections15.Predicate; import java.io.Serializable; /** * Predicate implementation that returns the opposite of the decorated predicate. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:24 $ * @since Commons Collections 3.0 */ public final class NotPredicate implements Predicate, PredicateDecorator, Serializable { /** * Serial version UID */ static final long serialVersionUID = -2654603322338049674L; /** * The predicate to decorate */ private final Predicate iPredicate; /** * Factory to create the not predicate. * * @param predicate the predicate to decorate, not null * @return the predicate * @throws IllegalArgumentException if the predicate is null */ public static Predicate getInstance(Predicate predicate) { if (predicate == null) { throw new IllegalArgumentException("Predicate must not be null"); } return new NotPredicate(predicate); } /** * Constructor that performs no validation. * Use getInstance if you want that. * * @param predicate the predicate to call after the null check */ public NotPredicate(Predicate predicate) { super(); iPredicate = predicate; } /** * Evaluates the predicate returning the opposite to the stored predicate. * * @param object the input object * @return true if predicate returns false */ public boolean evaluate(T object) { return !(iPredicate.evaluate(object)); } /** * Gets the predicate being decorated. * * @return the predicate as the only element in an array * @since Commons Collections 3.1 */ public Predicate[] getPredicates() { return new Predicate[]{iPredicate}; } } collections-generic-4.01/src/java/org/apache/commons/collections15/functors/ConstantTransformer.java0000644000175000017500000000537210464140765034213 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.functors; import org.apache.commons.collections15.Transformer; import java.io.Serializable; /** * Transformer implementation that returns the same constant each time. *

      * No check is made that the object is immutable. In general, only immutable * objects should use the constant factory. Mutable objects should * use the prototype factory. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:24 $ * @since Commons Collections 3.0 */ public class ConstantTransformer implements Transformer, Serializable { /** * Serial version UID */ static final long serialVersionUID = 6374440726369055124L; /** * Returns null each time */ public static final Transformer NULL_INSTANCE = new ConstantTransformer(null); /** * The closures to call in turn */ private final T iConstant; /** * Transformer method that performs validation. * * @param constantToReturn the constant object to return each time in the factory * @return the constant factory. */ public static Transformer getInstance(T constantToReturn) { if (constantToReturn == null) { return NULL_INSTANCE; } return new ConstantTransformer(constantToReturn); } /** * Constructor that performs no validation. * Use getInstance if you want that. * * @param constantToReturn the constant to return each time */ public ConstantTransformer(T constantToReturn) { super(); iConstant = constantToReturn; } /** * Transforms the input by ignoring it and returning the stored constant instead. * * @param input the input object which is ignored * @return the stored constant */ public T transform(Object input) { return iConstant; } /** * Gets the constant. * * @return the constant * @since Commons Collections 3.1 */ public T getConstant() { return iConstant; } } collections-generic-4.01/src/java/org/apache/commons/collections15/functors/NullPredicate.java0000644000175000017500000000355610464140756032734 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.functors; import org.apache.commons.collections15.Predicate; import java.io.Serializable; /** * Predicate implementation that returns true if the input is null. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:24 $ * @since Commons Collections 3.0 */ public final class NullPredicate implements Predicate, Serializable { /** * Serial version UID */ static final long serialVersionUID = 7533784454832764388L; /** * Singleton predicate instance */ public static final Predicate INSTANCE = new NullPredicate(); /** * Factory returning the singleton instance. * * @return the singleton instance * @since Commons Collections 3.1 */ public static Predicate getInstance() { return INSTANCE; } /** * Restricted constructor. */ private NullPredicate() { super(); } /** * Evaluates the predicate returning true if the input is null. * * @param object the input object * @return true if input is null */ public boolean evaluate(T object) { return (object == null); } } collections-generic-4.01/src/java/org/apache/commons/collections15/functors/InstantiateFactory.java0000644000175000017500000001163110464140764034004 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.functors; import org.apache.commons.collections15.Factory; import org.apache.commons.collections15.FunctorException; import java.io.Serializable; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; /** * Factory implementation that creates a new object instance by reflection. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:24 $ * @since Commons Collections 3.0 */ public class InstantiateFactory implements Factory, Serializable { /** * The serial version */ static final long serialVersionUID = -7732226881069447957L; /** * The class to create */ private final Class iClassToInstantiate; /** * The constructor parameter types */ private final Class[] iParamTypes; /** * The constructor arguments */ private final Object[] iArgs; /** * The constructor */ private transient Constructor iConstructor = null; /** * Factory method that performs validation. * * @param classToInstantiate the class to instantiate, not null * @param paramTypes the constructor parameter types * @param args the constructor arguments * @return a new instantiate factory */ public static Factory getInstance(Class classToInstantiate, Class[] paramTypes, Object[] args) { if (classToInstantiate == null) { throw new IllegalArgumentException("Class to instantiate must not be null"); } if (((paramTypes == null) && (args != null)) || ((paramTypes != null) && (args == null)) || ((paramTypes != null) && (args != null) && (paramTypes.length != args.length))) { throw new IllegalArgumentException("Parameter types must match the arguments"); } if (paramTypes == null || paramTypes.length == 0) { return new InstantiateFactory(classToInstantiate); } else { paramTypes = (Class[]) paramTypes.clone(); args = (Object[]) args.clone(); return new InstantiateFactory(classToInstantiate, paramTypes, args); } } /** * Constructor that performs no validation. * Use getInstance if you want that. * * @param classToInstantiate the class to instantiate */ public InstantiateFactory(Class classToInstantiate) { super(); iClassToInstantiate = classToInstantiate; iParamTypes = null; iArgs = null; findConstructor(); } /** * Constructor that performs no validation. * Use getInstance if you want that. * * @param classToInstantiate the class to instantiate * @param paramTypes the constructor parameter types, not cloned * @param args the constructor arguments, not cloned */ public InstantiateFactory(Class classToInstantiate, Class[] paramTypes, Object[] args) { super(); iClassToInstantiate = classToInstantiate; iParamTypes = paramTypes; iArgs = args; findConstructor(); } /** * Find the Constructor for the class specified. */ private void findConstructor() { try { iConstructor = iClassToInstantiate.getConstructor(iParamTypes); } catch (NoSuchMethodException ex) { throw new IllegalArgumentException("InstantiateFactory: The constructor must exist and be public "); } } /** * Creates an object using the stored constructor. * * @return the new object */ public T create() { // needed for post-serialization if (iConstructor == null) { findConstructor(); } try { return (T) iConstructor.newInstance(iArgs); } catch (InstantiationException ex) { throw new FunctorException("InstantiateFactory: InstantiationException", ex); } catch (IllegalAccessException ex) { throw new FunctorException("InstantiateFactory: Constructor must be public", ex); } catch (InvocationTargetException ex) { throw new FunctorException("InstantiateFactory: Constructor threw an exception", ex); } } } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootcollections-generic-4.01/src/java/org/apache/commons/collections15/functors/TransformedPredicate.javacollections-generic-4.01/src/java/org/apache/commons/collections15/functors/TransformedPredicate.jav0000644000175000017500000000732410464140762034137 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.functors; import org.apache.commons.collections15.Predicate; import org.apache.commons.collections15.Transformer; import java.io.Serializable; /** * Predicate implementation that transforms the given object before invoking * another Predicate. *

      * Note: This class cannot suppport generics without breaking the {@link PredicateDecorator} interface. * * @author Matt Hall, John Watkinson, Alban Peignier * @author Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:24 $ * @since Commons Collections 3.1 */ public final class TransformedPredicate implements Predicate, PredicateDecorator, Serializable { /** * Serial version UID */ static final long serialVersionUID = -5596090919668315834L; /** * The transformer to call */ private final Transformer iTransformer; /** * The predicate to call */ private final Predicate iPredicate; /** * Factory to create the predicate. * * @param transformer the transformer to call * @param predicate the predicate to call with the result of the transform * @return the predicate * @throws IllegalArgumentException if the transformer or the predicate is null */ public static Predicate getInstance(Transformer transformer, Predicate predicate) { if (transformer == null) { throw new IllegalArgumentException("The transformer to call must not be null"); } if (predicate == null) { throw new IllegalArgumentException("The predicate to call must not be null"); } return new TransformedPredicate(transformer, predicate); } /** * Constructor that performs no validation. * Use getInstance if you want that. * * @param transformer the transformer to use * @param predicate the predicate to decorate */ public TransformedPredicate(Transformer transformer, Predicate predicate) { iTransformer = transformer; iPredicate = predicate; } /** * Evaluates the predicate returning the result of the decorated predicate * once the input has been transformed * * @param object the input object which will be transformed * @return true if decorated predicate returns true */ public boolean evaluate(I object) { O result = iTransformer.transform(object); return iPredicate.evaluate(result); } /** * Gets the predicate being decorated. *

      * Not type-safe in 1.5. *

      * * @return the predicate as the only element in an array * @since Commons Collections 3.1 */ public Predicate[] getPredicates() { return new Predicate[]{iPredicate}; } /** * Gets the transformer in use. * * @return the transformer */ public Transformer getTransformer() { return iTransformer; } } collections-generic-4.01/src/java/org/apache/commons/collections15/functors/NOPClosure.java0000644000175000017500000000331210464140762032155 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.functors; import org.apache.commons.collections15.Closure; import java.io.Serializable; /** * Closure implementation that does nothing. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:24 $ * @since Commons Collections 3.0 */ public class NOPClosure implements Closure, Serializable { /** * Serial version UID */ static final long serialVersionUID = 3518477308466486130L; /** * Singleton predicate instance */ public static final Closure INSTANCE = new NOPClosure(); /** * Factory returning the singleton instance. * * @return the singleton instance * @since Commons Collections 3.1 */ public static Closure getInstance() { return INSTANCE; } /** * Constructor */ private NOPClosure() { super(); } /** * Do nothing. * * @param input the input object */ public void execute(T input) { // do nothing } } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootcollections-generic-4.01/src/java/org/apache/commons/collections15/functors/TransformerPredicate.javacollections-generic-4.01/src/java/org/apache/commons/collections15/functors/TransformerPredicate.jav0000644000175000017500000000601210464140765034151 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.functors; import org.apache.commons.collections15.FunctorException; import org.apache.commons.collections15.Predicate; import org.apache.commons.collections15.Transformer; import java.io.Serializable; /** * Predicate implementation that returns the result of a transformer. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:24 $ * @since Commons Collections 3.0 */ public final class TransformerPredicate implements Predicate, Serializable { /** * Serial version UID */ static final long serialVersionUID = -2407966402920578741L; /** * The transformer to call */ private final Transformer iTransformer; /** * Factory to create the predicate. * * @param transformer the transformer to decorate * @return the predicate * @throws IllegalArgumentException if the transformer is null */ public static Predicate getInstance(Transformer transformer) { if (transformer == null) { throw new IllegalArgumentException("The transformer to call must not be null"); } return new TransformerPredicate(transformer); } /** * Constructor that performs no validation. * Use getInstance if you want that. * * @param transformer the transformer to decorate */ public TransformerPredicate(Transformer transformer) { super(); iTransformer = transformer; } /** * Evaluates the predicate returning the result of the decorated transformer. * * @param object the input object * @return true if decorated transformer returns Boolean.TRUE * @throws FunctorException if the transformer returns an invalid type */ public boolean evaluate(T object) { Boolean result = iTransformer.transform(object); if (result == null) { throw new FunctorException("Transformer must return an instanceof Boolean, it was a " + (result == null ? "null object" : result.getClass().getName())); } return result.booleanValue(); } /** * Gets the transformer. * * @return the transformer * @since Commons Collections 3.1 */ public Transformer getTransformer() { return iTransformer; } } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootcollections-generic-4.01/src/java/org/apache/commons/collections15/functors/PredicateTransformer.javacollections-generic-4.01/src/java/org/apache/commons/collections15/functors/PredicateTransformer.jav0000644000175000017500000000520410464140755034152 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.functors; import org.apache.commons.collections15.Predicate; import org.apache.commons.collections15.Transformer; import java.io.Serializable; /** * Transformer implementation that calls a Predicate using the input object * and then returns the input. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:24 $ * @since Commons Collections 3.0 */ public class PredicateTransformer implements Transformer, Serializable { /** * Serial version UID */ static final long serialVersionUID = 5278818408044349346L; /** * The closure to wrap */ private final Predicate iPredicate; /** * Factory method that performs validation. * * @param predicate the predicate to call, not null * @return the predicate transformer * @throws IllegalArgumentException if the predicate is null */ public static Transformer getInstance(Predicate predicate) { if (predicate == null) { throw new IllegalArgumentException("Predicate must not be null"); } return new PredicateTransformer(predicate); } /** * Constructor that performs no validation. * Use getInstance if you want that. * * @param predicate the predicate to call, not null */ public PredicateTransformer(Predicate predicate) { super(); iPredicate = predicate; } /** * Transforms the input to result by calling a predicate. * * @param input the input object to transform * @return the transformed result */ public Boolean transform(T input) { return (iPredicate.evaluate(input) ? Boolean.TRUE : Boolean.FALSE); } /** * Gets the predicate. * * @return the predicate * @since Commons Collections 3.1 */ public Predicate getPredicate() { return iPredicate; } } collections-generic-4.01/src/java/org/apache/commons/collections15/functors/MapTransformer.java0000644000175000017500000000473010464140762033131 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.functors; import org.apache.commons.collections15.Transformer; import java.io.Serializable; import java.util.Map; /** * Transformer implementation that returns the value held in a specified map * using the input parameter as a key. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:24 $ * @since Commons Collections 3.0 */ public final class MapTransformer implements Transformer, Serializable { /** * Serial version UID */ static final long serialVersionUID = 862391807045468939L; /** * The map of data to lookup in */ private final Map iMap; /** * Factory to create the transformer. *

      * If the map is null, a transformer that always returns null is returned. * * @param map the map, not cloned * @return the transformer */ public static Transformer getInstance(Map map) { if (map == null) { return ConstantTransformer.NULL_INSTANCE; } return new MapTransformer(map); } /** * Constructor that performs no validation. * Use getInstance if you want that. * * @param map the map to use for lookup, not cloned */ private MapTransformer(Map map) { super(); iMap = map; } /** * Transforms the input to result by looking it up in a Map. * * @param input the input object to transform * @return the transformed result */ public O transform(I input) { return iMap.get(input); } /** * Gets the map to lookup in. * * @return the map * @since Commons Collections 3.1 */ public Map getMap() { return iMap; } } collections-generic-4.01/src/java/org/apache/commons/collections15/functors/PredicateDecorator.java0000644000175000017500000000263710464140762033740 0ustar giovannigiovanni// GenericsNote: Converted (no generics required). /* * Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.functors; import org.apache.commons.collections15.Predicate; /** * Defines a predicate that decorates one or more other predicates. *

      * This interface enables tools to access the decorated predicates. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:24 $ * @since Commons Collections 3.1 */ public interface PredicateDecorator extends Predicate { /** * Gets the predicates being decorated as an array. *

      * The array may be the internal data structure of the predicate and thus * should not be altered. * * @return the predicates being decorated */ Predicate[] getPredicates(); } collections-generic-4.01/src/java/org/apache/commons/collections15/functors/OnePredicate.java0000644000175000017500000000727710464140761032543 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.functors; import org.apache.commons.collections15.Predicate; import java.io.Serializable; import java.util.Collection; /** * Predicate implementation that returns true if only one of the predicates return true. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:24 $ * @since Commons Collections 3.0 */ public final class OnePredicate implements Predicate, PredicateDecorator, Serializable { /** * Serial version UID */ static final long serialVersionUID = -8125389089924745785L; /** * The array of predicates to call */ private final Predicate[] iPredicates; /** * Factory to create the predicate. * * @param predicates the predicates to check, cloned, not null * @return the any predicate * @throws IllegalArgumentException if the predicates array is null * @throws IllegalArgumentException if the predicates array has less than 2 elements * @throws IllegalArgumentException if any predicate in the array is null */ public static Predicate getInstance(Predicate[] predicates) { FunctorUtils.validateMin2(predicates); predicates = FunctorUtils.copy(predicates); return new OnePredicate(predicates); } /** * Factory to create the predicate. * * @param predicates the predicates to check, cloned, not null * @return the one predicate * @throws IllegalArgumentException if the predicates array is null * @throws IllegalArgumentException if any predicate in the array is null * @throws IllegalArgumentException if the predicates array has less than 2 elements */ public static Predicate getInstance(Collection> predicates) { Predicate[] preds = FunctorUtils.validate(predicates); return new OnePredicate(preds); } /** * Constructor that performs no validation. * Use getInstance if you want that. * * @param predicates the predicates to check, not cloned, not null */ public OnePredicate(Predicate[] predicates) { super(); iPredicates = predicates; } /** * Evaluates the predicate returning true if only one decorated predicate * returns true. * * @param object the input object * @return true if only one decorated predicate returns true */ public boolean evaluate(T object) { boolean match = false; for (int i = 0; i < iPredicates.length; i++) { if (iPredicates[i].evaluate(object)) { if (match) { return false; } match = true; } } return match; } /** * Gets the predicates, do not modify the array. * * @return the predicates * @since Commons Collections 3.1 */ public Predicate[] getPredicates() { return iPredicates; } } collections-generic-4.01/src/java/org/apache/commons/collections15/functors/PrototypeFactory.java0000644000175000017500000001560010464140762033524 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.functors; import org.apache.commons.collections15.Factory; import org.apache.commons.collections15.FunctorException; import java.io.*; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; /** * Factory implementation that creates a new instance each time based on a prototype. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:24 $ * @since Commons Collections 3.0 */ public class PrototypeFactory { /** * Factory method that performs validation. *

      * Creates a Factory that will return a clone of the same prototype object * each time the factory is used. The prototype will be cloned using one of these * techniques (in order): *

        *
      • public clone method *
      • public copy constructor *
      • serialization clone *
          * * @param prototype the object to clone each time in the factory * @return the prototype factory * @throws IllegalArgumentException if the prototype is null * @throws IllegalArgumentException if the prototype cannot be cloned */ public static Factory getInstance(T prototype) { if (prototype == null) { return ConstantFactory.NULL_INSTANCE; } try { Method method = prototype.getClass().getMethod("clone", null); return new PrototypeCloneFactory(prototype, method); } catch (NoSuchMethodException ex) { try { prototype.getClass().getConstructor(new Class[]{prototype.getClass()}); return new InstantiateFactory((Class) prototype.getClass(), new Class[]{prototype.getClass()}, new Object[]{prototype}); } catch (NoSuchMethodException ex2) { if (prototype instanceof Serializable) { return new PrototypeSerializationFactory((Serializable) prototype); } } } throw new IllegalArgumentException("The prototype must be cloneable via a public clone method"); } /** * Constructor that performs no validation. * Use getInstance if you want that. */ private PrototypeFactory() { super(); } // PrototypeCloneFactory //----------------------------------------------------------------------- /** * PrototypeCloneFactory creates objects by copying a prototype using the clone method. */ static class PrototypeCloneFactory implements Factory, Serializable { /** * The serial version */ static final long serialVersionUID = 5604271422565175555L; /** * The object to clone each time */ private final T iPrototype; /** * The method used to clone */ private transient Method iCloneMethod; /** * Constructor to store prototype. */ private PrototypeCloneFactory(T prototype, Method method) { super(); iPrototype = prototype; iCloneMethod = method; } /** * Find the Clone method for the class specified. */ private void findCloneMethod() { try { iCloneMethod = iPrototype.getClass().getMethod("clone", null); } catch (NoSuchMethodException ex) { throw new IllegalArgumentException("PrototypeCloneFactory: The clone method must exist and be public "); } } /** * Creates an object by calling the clone method. * * @return the new object */ public T create() { // needed for post-serialization if (iCloneMethod == null) { findCloneMethod(); } try { return (T) iCloneMethod.invoke(iPrototype, null); } catch (IllegalAccessException ex) { throw new FunctorException("PrototypeCloneFactory: Clone method must be public", ex); } catch (InvocationTargetException ex) { throw new FunctorException("PrototypeCloneFactory: Clone method threw an exception", ex); } } } // PrototypeSerializationFactory //----------------------------------------------------------------------- /** * PrototypeSerializationFactory creates objects by cloning a prototype using serialization. */ static class PrototypeSerializationFactory implements Factory, Serializable { /** * The serial version */ static final long serialVersionUID = -8704966966139178833L; /** * The object to clone via serialization each time */ private final Serializable iPrototype; /** * Constructor to store prototype */ private PrototypeSerializationFactory(Serializable prototype) { super(); iPrototype = prototype; } /** * Creates an object using serialization. * * @return the new object */ public T create() { ByteArrayOutputStream baos = new ByteArrayOutputStream(512); ByteArrayInputStream bais = null; try { ObjectOutputStream out = new ObjectOutputStream(baos); out.writeObject(iPrototype); bais = new ByteArrayInputStream(baos.toByteArray()); ObjectInputStream in = new ObjectInputStream(bais); return (T) in.readObject(); } catch (ClassNotFoundException ex) { throw new FunctorException(ex); } catch (IOException ex) { throw new FunctorException(ex); } finally { try { if (bais != null) { bais.close(); } } catch (IOException ex) { // ignore } try { if (baos != null) { baos.close(); } } catch (IOException ex) { // ignore } } } } } collections-generic-4.01/src/java/org/apache/commons/collections15/functors/NullIsTruePredicate.java0000644000175000017500000000534710464140756034070 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.functors; import org.apache.commons.collections15.Predicate; import java.io.Serializable; /** * Predicate implementation that returns true if the input is null. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:24 $ * @since Commons Collections 3.0 */ public final class NullIsTruePredicate implements Predicate, PredicateDecorator, Serializable { /** * Serial version UID */ static final long serialVersionUID = -7625133768987126273L; /** * The predicate to decorate */ private final Predicate iPredicate; /** * Factory to create the null true predicate. * * @param predicate the predicate to decorate, not null * @return the predicate * @throws IllegalArgumentException if the predicate is null */ public static Predicate getInstance(Predicate predicate) { if (predicate == null) { throw new IllegalArgumentException("Predicate must not be null"); } return new NullIsTruePredicate(predicate); } /** * Constructor that performs no validation. * Use getInstance if you want that. * * @param predicate the predicate to call after the null check */ public NullIsTruePredicate(Predicate predicate) { super(); iPredicate = predicate; } /** * Evaluates the predicate returning the result of the decorated predicate * once a null check is performed. * * @param object the input object * @return true if decorated predicate returns true or input is null */ public boolean evaluate(T object) { if (object == null) { return true; } return iPredicate.evaluate(object); } /** * Gets the predicate being decorated. * * @return the predicate as the only element in an array * @since Commons Collections 3.1 */ public Predicate[] getPredicates() { return new Predicate[]{iPredicate}; } } collections-generic-4.01/src/java/org/apache/commons/collections15/functors/NonePredicate.java0000644000175000017500000000706410464140754032715 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.functors; import org.apache.commons.collections15.Predicate; import java.io.Serializable; import java.util.Collection; /** * Predicate implementation that returns true if none of the predicates return true. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:24 $ * @since Commons Collections 3.0 */ public final class NonePredicate implements Predicate, PredicateDecorator, Serializable { /** * Serial version UID */ static final long serialVersionUID = 2007613066565892961L; /** * The array of predicates to call */ private final Predicate[] iPredicates; /** * Factory to create the predicate. * * @param predicates the predicates to check, cloned, not null * @return the any predicate * @throws IllegalArgumentException if the predicates array is null * @throws IllegalArgumentException if the predicates array has less than 2 elements * @throws IllegalArgumentException if any predicate in the array is null */ public static Predicate getInstance(Predicate[] predicates) { FunctorUtils.validateMin2(predicates); predicates = FunctorUtils.copy(predicates); return new NonePredicate(predicates); } /** * Factory to create the predicate. * * @param predicates the predicates to check, cloned, not null * @return the one predicate * @throws IllegalArgumentException if the predicates array is null * @throws IllegalArgumentException if any predicate in the array is null * @throws IllegalArgumentException if the predicates array has less than 2 elements */ public static Predicate getInstance(Collection> predicates) { Predicate[] preds = FunctorUtils.validate(predicates); return new NonePredicate(preds); } /** * Constructor that performs no validation. * Use getInstance if you want that. * * @param predicates the predicates to check, not cloned, not null */ public NonePredicate(Predicate[] predicates) { super(); iPredicates = predicates; } /** * Evaluates the predicate returning false if any stored predicate returns false. * * @param object the input object * @return true if none of decorated predicates return true */ public boolean evaluate(T object) { for (int i = 0; i < iPredicates.length; i++) { if (iPredicates[i].evaluate(object)) { return false; } } return true; } /** * Gets the predicates, do not modify the array. * * @return the predicates * @since Commons Collections 3.1 */ public Predicate[] getPredicates() { return iPredicates; } } collections-generic-4.01/src/java/org/apache/commons/collections15/functors/TruePredicate.java0000644000175000017500000000347410464140764032737 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.functors; import org.apache.commons.collections15.Predicate; import java.io.Serializable; /** * Predicate implementation that always returns true. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:24 $ * @since Commons Collections 3.0 */ public final class TruePredicate implements Predicate, Serializable { /** * Serial version UID */ static final long serialVersionUID = 3374767158756189740L; /** * Singleton predicate instance */ public static final Predicate INSTANCE = new TruePredicate(); /** * Factory returning the singleton instance. * * @return the singleton instance * @since Commons Collections 3.1 */ public static Predicate getInstance() { return INSTANCE; } /** * Restricted constructor. */ private TruePredicate() { super(); } /** * Evaluates the predicate returning true always. * * @param object the input object * @return true always */ public boolean evaluate(T object) { return true; } } ././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootcollections-generic-4.01/src/java/org/apache/commons/collections15/functors/NullIsExceptionPredicate.javacollections-generic-4.01/src/java/org/apache/commons/collections15/functors/NullIsExceptionPredicate0000644000175000017500000000561310464140757034164 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.functors; import org.apache.commons.collections15.FunctorException; import org.apache.commons.collections15.Predicate; import java.io.Serializable; /** * Predicate implementation that throws an exception if the input is null. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:24 $ * @since Commons Collections 3.0 */ public final class NullIsExceptionPredicate implements Predicate, PredicateDecorator, Serializable { /** * Serial version UID */ static final long serialVersionUID = 3243449850504576071L; /** * The predicate to decorate */ private final Predicate iPredicate; /** * Factory to create the null exception predicate. * * @param predicate the predicate to decorate, not null * @return the predicate * @throws IllegalArgumentException if the predicate is null */ public static Predicate getInstance(Predicate predicate) { if (predicate == null) { throw new IllegalArgumentException("Predicate must not be null"); } return new NullIsExceptionPredicate(predicate); } /** * Constructor that performs no validation. * Use getInstance if you want that. * * @param predicate the predicate to call after the null check */ public NullIsExceptionPredicate(Predicate predicate) { super(); iPredicate = predicate; } /** * Evaluates the predicate returning the result of the decorated predicate * once a null check is performed. * * @param object the input object * @return true if decorated predicate returns true * @throws FunctorException if input is null */ public boolean evaluate(T object) { if (object == null) { throw new FunctorException("Input Object must not be null"); } return iPredicate.evaluate(object); } /** * Gets the predicate being decorated. * * @return the predicate as the only element in an array * @since Commons Collections 3.1 */ public Predicate[] getPredicates() { return new Predicate[]{iPredicate}; } } collections-generic-4.01/src/java/org/apache/commons/collections15/functors/WhileClosure.java0000644000175000017500000000756010464140760032600 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.functors; import org.apache.commons.collections15.Closure; import org.apache.commons.collections15.Predicate; import java.io.Serializable; /** * Closure implementation that executes a closure repeatedly until a condition is met, * like a do-while or while loop. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:24 $ * @since Commons Collections 3.0 */ public class WhileClosure implements Closure, Serializable { /** * Serial version UID */ static final long serialVersionUID = -3110538116913760108L; /** * The test condition */ private final Predicate iPredicate; /** * The closure to call */ private final Closure iClosure; /** * The flag, true is a do loop, false is a while */ private final boolean iDoLoop; /** * Factory method that performs validation. * * @param predicate the predicate used to evaluate when the loop terminates, not null * @param closure the closure the execute, not null * @param doLoop true to act as a do-while loop, always executing the closure once * @return the while closure * @throws IllegalArgumentException if the predicate or closure is null */ public static Closure getInstance(Predicate predicate, Closure closure, boolean doLoop) { if (predicate == null) { throw new IllegalArgumentException("Predicate must not be null"); } if (closure == null) { throw new IllegalArgumentException("Closure must not be null"); } return new WhileClosure(predicate, closure, doLoop); } /** * Constructor that performs no validation. * Use getInstance if you want that. * * @param predicate the predicate used to evaluate when the loop terminates, not null * @param closure the closure the execute, not null * @param doLoop true to act as a do-while loop, always executing the closure once */ public WhileClosure(Predicate predicate, Closure closure, boolean doLoop) { super(); iPredicate = predicate; iClosure = closure; iDoLoop = doLoop; } /** * Executes the closure until the predicate is false. * * @param input the input object */ public void execute(T input) { if (iDoLoop) { iClosure.execute(input); } while (iPredicate.evaluate(input)) { iClosure.execute(input); } } /** * Gets the predicate in use. * * @return the predicate * @since Commons Collections 3.1 */ public Predicate getPredicate() { return iPredicate; } /** * Gets the closure. * * @return the closure * @since Commons Collections 3.1 */ public Closure getClosure() { return iClosure; } /** * Is the loop a do-while loop. * * @return true is do-while, false if while * @since Commons Collections 3.1 */ public boolean isDoLoop() { return iDoLoop; } } collections-generic-4.01/src/java/org/apache/commons/collections15/functors/ChainedTransformer.java0000644000175000017500000001215710464140762033751 0ustar giovannigiovanni// GenericsNote: Converted, but only partially type-safe. /* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.functors; import org.apache.commons.collections15.Transformer; import java.io.Serializable; import java.util.Collection; import java.util.Iterator; /** * Transformer implementation that chains the specified transformers together. *

          * The input object is passed to the first transformer. The transformed result * is passed to the second transformer and so on. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:24 $ * @since Commons Collections 3.0 */ public class ChainedTransformer implements Transformer, Serializable { /** * Serial version UID */ static final long serialVersionUID = 3514945074733160196L; /** * The transformers to call in turn */ private final Transformer[] iTransformers; /** * Factory method that performs validation and copies the parameter array. * * @param transformers the transformers to chain, copied, no nulls * @return the chained transformer * @throws IllegalArgumentException if the transformers array is null * @throws IllegalArgumentException if any transformer in the array is null */ public static Transformer getInstance(Transformer[] transformers) { FunctorUtils.validate(transformers); if (transformers.length == 0) { return NOPTransformer.INSTANCE; } transformers = FunctorUtils.copy(transformers); return new ChainedTransformer(transformers); } /** * Create a new Transformer that calls each transformer in turn, passing the * result into the next transformer. The ordering is that of the iterator() * method on the collection. * * @param transformers a collection of transformers to chain * @return the chained transformer * @throws IllegalArgumentException if the transformers collection is null * @throws IllegalArgumentException if any transformer in the collection is null */ public static Transformer getInstance(Collection transformers) { if (transformers == null) { throw new IllegalArgumentException("Transformer collection must not be null"); } if (transformers.size() == 0) { return NOPTransformer.INSTANCE; } // convert to array like this to guarantee iterator() ordering Transformer[] cmds = new Transformer[transformers.size()]; int i = 0; for (Iterator it = transformers.iterator(); it.hasNext();) { cmds[i++] = it.next(); } FunctorUtils.validate(cmds); return new ChainedTransformer(cmds); } /** * Factory method that performs validation. * * @param transformer1 the first transformer, not null * @param transformer2 the second transformer, not null * @return the chained transformer * @throws IllegalArgumentException if either transformer is null */ public static Transformer getInstance(Transformer transformer1, Transformer transformer2) { if (transformer1 == null || transformer2 == null) { throw new IllegalArgumentException("Transformers must not be null"); } Transformer[] transformers = new Transformer[]{transformer1, transformer2}; return new ChainedTransformer(transformers); } /** * Constructor that performs no validation. * Use getInstance if you want that. * * @param transformers the transformers to chain, not copied, no nulls */ public ChainedTransformer(Transformer[] transformers) { super(); iTransformers = transformers; } /** * Transforms the input to result via each decorated transformer * * @param object the input object passed to the first transformer * @return the transformed result */ public O transform(I object) { Object intermediate = object; for (int i = 0; i < iTransformers.length; i++) { intermediate = iTransformers[i].transform(intermediate); } return (O) intermediate; } /** * Gets the transformers, do not modify the array. * * @return the transformers * @since Commons Collections 3.1 */ public Transformer[] getTransformers() { return iTransformers; } } collections-generic-4.01/src/java/org/apache/commons/collections15/functors/UniquePredicate.java0000644000175000017500000000412710464140763033261 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.functors; import org.apache.commons.collections15.Predicate; import java.io.Serializable; import java.util.HashSet; import java.util.Set; /** * Predicate implementation that returns true the first time an object is * passed into the predicate. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:24 $ * @since Commons Collections 3.0 */ public final class UniquePredicate implements Predicate, Serializable { /** * Serial version UID */ static final long serialVersionUID = -3319417438027438040L; /** * The set of previously seen objects */ private final Set iSet = new HashSet(); /** * Factory to create the predicate. * * @return the predicate * @throws IllegalArgumentException if the predicate is null */ public static Predicate getInstance() { return new UniquePredicate(); } /** * Constructor that performs no validation. * Use getInstance if you want that. */ public UniquePredicate() { super(); } /** * Evaluates the predicate returning true if the input object hasn't been * received yet. * * @param object the input object * @return true if this is the first time the object is seen */ public boolean evaluate(T object) { return iSet.add(object); } } collections-generic-4.01/src/java/org/apache/commons/collections15/functors/OrPredicate.java0000644000175000017500000000606710464140765032402 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.functors; import org.apache.commons.collections15.Predicate; import java.io.Serializable; /** * Predicate implementation that returns true if either of the predicates return true. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:24 $ * @since Commons Collections 3.0 */ public final class OrPredicate implements Predicate, PredicateDecorator, Serializable { /** * Serial version UID */ static final long serialVersionUID = -8791518325735182855L; /** * The array of predicates to call */ private final Predicate iPredicate1; /** * The array of predicates to call */ private final Predicate iPredicate2; /** * Factory to create the predicate. * * @param predicate1 the first predicate to check, not null * @param predicate2 the second predicate to check, not null * @return the and predicate * @throws IllegalArgumentException if either predicate is null */ public static Predicate getInstance(Predicate predicate1, Predicate predicate2) { if (predicate1 == null || predicate2 == null) { throw new IllegalArgumentException("Predicate must not be null"); } return new OrPredicate(predicate1, predicate2); } /** * Constructor that performs no validation. * Use getInstance if you want that. * * @param predicate1 the first predicate to check, not null * @param predicate2 the second predicate to check, not null */ public OrPredicate(Predicate predicate1, Predicate predicate2) { super(); iPredicate1 = predicate1; iPredicate2 = predicate2; } /** * Evaluates the predicate returning true if either predicate returns true. * * @param object the input object * @return true if either decorated predicate returns true */ public boolean evaluate(T object) { return (iPredicate1.evaluate(object) || iPredicate2.evaluate(object)); } /** * Gets the two predicates being decorated as an array. * * @return the predicates * @since Commons Collections 3.1 */ public Predicate[] getPredicates() { return new Predicate[]{iPredicate1, iPredicate2}; } } collections-generic-4.01/src/java/org/apache/commons/collections15/functors/TransformerClosure.java0000644000175000017500000000511410464140761034024 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.functors; import org.apache.commons.collections15.Closure; import org.apache.commons.collections15.Transformer; import java.io.Serializable; /** * Closure implementation that calls a Transformer using the input object * and ignore the result. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:24 $ * @since Commons Collections 3.0 */ public class TransformerClosure implements Closure, Serializable { /** * Serial version UID */ static final long serialVersionUID = -5194992589193388969L; /** * The transformer to wrap */ private final Transformer iTransformer; /** * Factory method that performs validation. *

          * A null transformer will return the NOPClosure. * * @param transformer the transformer to call, null means nop * @return the transformer closure */ public static Closure getInstance(Transformer transformer) { if (transformer == null) { return NOPClosure.INSTANCE; } return new TransformerClosure(transformer); } /** * Constructor that performs no validation. * Use getInstance if you want that. * * @param transformer the transformer to call, not null */ public TransformerClosure(Transformer transformer) { super(); iTransformer = transformer; } /** * Executes the closure by calling the decorated transformer. * * @param input the input object */ public void execute(I input) { iTransformer.transform(input); } /** * Gets the transformer. * * @return the transformer * @since Commons Collections 3.1 */ public Transformer getTransformer() { return iTransformer; } } collections-generic-4.01/src/java/org/apache/commons/collections15/functors/ExceptionPredicate.java0000644000175000017500000000373610464140764033757 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.functors; import org.apache.commons.collections15.FunctorException; import org.apache.commons.collections15.Predicate; import java.io.Serializable; /** * Predicate implementation that always throws an exception. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:24 $ * @since Commons Collections 3.0 */ public final class ExceptionPredicate implements Predicate, Serializable { /** * Serial version UID */ static final long serialVersionUID = 7179106032121985545L; /** * Singleton predicate instance */ public static final Predicate INSTANCE = new ExceptionPredicate(); /** * Factory returning the singleton instance. * * @return the singleton instance * @since Commons Collections 3.1 */ public static Predicate getInstance() { return INSTANCE; } /** * Restricted constructor. */ private ExceptionPredicate() { super(); } /** * Evaluates the predicate always throwing an exception. * * @param object the input object * @return never * @throws FunctorException always */ public boolean evaluate(T object) { throw new FunctorException("ExceptionPredicate invoked"); } } collections-generic-4.01/src/java/org/apache/commons/collections15/functors/ForClosure.java0000644000175000017500000000567610464140756032271 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.functors; import org.apache.commons.collections15.Closure; import java.io.Serializable; /** * Closure implementation that calls another closure n times, like a for loop. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:24 $ * @since Commons Collections 3.0 */ public class ForClosure implements Closure, Serializable { /** * Serial version UID */ static final long serialVersionUID = -1190120533393621674L; /** * The number of times to loop */ private final int iCount; /** * The closure to call */ private final Closure iClosure; /** * Factory method that performs validation. *

          * A null closure or zero count returns the NOPClosure. * A count of one returns the specified closure. * * @param count the number of times to execute the closure * @param closure the closure to execute, not null * @return the for closure */ public static Closure getInstance(int count, Closure closure) { if (count <= 0 || closure == null) { return NOPClosure.INSTANCE; } if (count == 1) { return closure; } return new ForClosure(count, closure); } /** * Constructor that performs no validation. * Use getInstance if you want that. * * @param count the number of times to execute the closure * @param closure the closure to execute, not null */ public ForClosure(int count, Closure closure) { super(); iCount = count; iClosure = closure; } /** * Executes the closure count times. * * @param input the input object */ public void execute(T input) { for (int i = 0; i < iCount; i++) { iClosure.execute(input); } } /** * Gets the closure. * * @return the closure * @since Commons Collections 3.1 */ public Closure getClosure() { return iClosure; } /** * Gets the count. * * @return the count * @since Commons Collections 3.1 */ public int getCount() { return iCount; } } collections-generic-4.01/src/java/org/apache/commons/collections15/functors/AndPredicate.java0000644000175000017500000000606010464140756032515 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.functors; import org.apache.commons.collections15.Predicate; import java.io.Serializable; /** * Predicate implementation that returns true if both the predicates return true. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:24 $ * @since Commons Collections 3.0 */ public final class AndPredicate implements Predicate, PredicateDecorator, Serializable { /** * Serial version UID */ static final long serialVersionUID = 4189014213763186912L; /** * The array of predicates to call */ private final Predicate iPredicate1; /** * The array of predicates to call */ private final Predicate iPredicate2; /** * Factory to create the predicate. * * @param predicate1 the first predicate to check, not null * @param predicate2 the second predicate to check, not null * @return the and predicate * @throws IllegalArgumentException if either predicate is null */ public static Predicate getInstance(Predicate predicate1, Predicate predicate2) { if (predicate1 == null || predicate2 == null) { throw new IllegalArgumentException("Predicate must not be null"); } return new AndPredicate(predicate1, predicate2); } /** * Constructor that performs no validation. * Use getInstance if you want that. * * @param predicate1 the first predicate to check, not null * @param predicate2 the second predicate to check, not null */ public AndPredicate(Predicate predicate1, Predicate predicate2) { super(); iPredicate1 = predicate1; iPredicate2 = predicate2; } /** * Evaluates the predicate returning true if both predicates return true. * * @param object the input object * @return true if both decorated predicates return true */ public boolean evaluate(T object) { return (iPredicate1.evaluate(object) && iPredicate2.evaluate(object)); } /** * Gets the two predicates being decorated as an array. * * @return the predicates * @since Commons Collections 3.1 */ public Predicate[] getPredicates() { return new Predicate[]{iPredicate1, iPredicate2}; } } collections-generic-4.01/src/java/org/apache/commons/collections15/functors/ConstantFactory.java0000644000175000017500000000511510464140760033306 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.functors; import org.apache.commons.collections15.Factory; import java.io.Serializable; /** * Factory implementation that returns the same constant each time. *

          * No check is made that the object is immutable. In general, only immutable * objects should use the constant factory. Mutable objects should * use the prototype factory. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:24 $ * @since Commons Collections 3.0 */ public class ConstantFactory implements Factory, Serializable { /** * Serial version UID */ static final long serialVersionUID = -3520677225766901240L; /** * Returns null each time */ public static final Factory NULL_INSTANCE = new ConstantFactory(null); /** * The closures to call in turn */ private final T iConstant; /** * Factory method that performs validation. * * @param constantToReturn the constant object to return each time in the factory * @return the constant factory. */ public static Factory getInstance(T constantToReturn) { if (constantToReturn == null) { return NULL_INSTANCE; } return new ConstantFactory(constantToReturn); } /** * Constructor that performs no validation. * Use getInstance if you want that. * * @param constantToReturn the constant to return each time */ public ConstantFactory(T constantToReturn) { super(); iConstant = constantToReturn; } /** * Always return constant. * * @return the stored constant value */ public T create() { return iConstant; } /** * Gets the constant. * * @return the constant * @since Commons Collections 3.1 */ public T getConstant() { return iConstant; } } collections-generic-4.01/src/java/org/apache/commons/collections15/functors/FunctorUtils.java0000644000175000017500000001375010464140765032637 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.functors; import org.apache.commons.collections15.Closure; import org.apache.commons.collections15.Predicate; import org.apache.commons.collections15.Transformer; import java.util.Collection; import java.util.Iterator; /** * Internal utilities for functors. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:24 $ * @since Commons Collections 3.0 */ class FunctorUtils { /** * Restricted constructor. */ private FunctorUtils() { super(); } /** * Clone the predicates to ensure that the internal reference can't be messed with. * * @param predicates the predicates to copy * @return the cloned predicates */ static Predicate[] copy(Predicate[] predicates) { if (predicates == null) { return null; } return (Predicate[]) predicates.clone(); } /** * Validate the predicates to ensure that all is well. * * @param predicates the predicates to validate */ static void validate(Predicate[] predicates) { if (predicates == null) { throw new IllegalArgumentException("The predicate array must not be null"); } for (int i = 0; i < predicates.length; i++) { if (predicates[i] == null) { throw new IllegalArgumentException("The predicate array must not contain a null predicate, index " + i + " was null"); } } } /** * Validate the predicates to ensure that all is well. * * @param predicates the predicates to validate */ static void validateMin2(Predicate[] predicates) { if (predicates == null) { throw new IllegalArgumentException("The predicate array must not be null"); } if (predicates.length < 2) { throw new IllegalArgumentException("At least 2 predicates must be specified in the predicate array, size was " + predicates.length); } for (int i = 0; i < predicates.length; i++) { if (predicates[i] == null) { throw new IllegalArgumentException("The predicate array must not contain a null predicate, index " + i + " was null"); } } } /** * Validate the predicates to ensure that all is well. * * @param predicates the predicates to validate * @return predicate array */ static Predicate[] validate(Collection> predicates) { if (predicates == null) { throw new IllegalArgumentException("The predicate collection must not be null"); } if (predicates.size() < 2) { throw new IllegalArgumentException("At least 2 predicates must be specified in the predicate collection, size was " + predicates.size()); } // convert to array like this to guarantee iterator() ordering Predicate[] preds = new Predicate[predicates.size()]; int i = 0; for (Iterator> it = predicates.iterator(); it.hasNext();) { preds[i] = it.next(); if (preds[i] == null) { throw new IllegalArgumentException("The predicate collection must not contain a null predicate, index " + i + " was null"); } i++; } return preds; } /** * Clone the closures to ensure that the internal reference can't be messed with. * * @param closures the closures to copy * @return the cloned closures */ static Closure[] copy(Closure[] closures) { if (closures == null) { return null; } return (Closure[]) closures.clone(); } /** * Validate the closures to ensure that all is well. * * @param closures the closures to validate */ static void validate(Closure[] closures) { if (closures == null) { throw new IllegalArgumentException("The closure array must not be null"); } for (int i = 0; i < closures.length; i++) { if (closures[i] == null) { throw new IllegalArgumentException("The closure array must not contain a null closure, index " + i + " was null"); } } } /** * Copy method * * @param transformers the transformers to copy * @return a clone of the transformers */ static Transformer[] copy(Transformer[] transformers) { if (transformers == null) { return null; } return (Transformer[]) transformers.clone(); } /** * Validate method * * @param transformers the transformers to validate */ static void validate(Transformer[] transformers) { if (transformers == null) { throw new IllegalArgumentException("The transformer array must not be null"); } for (int i = 0; i < transformers.length; i++) { if (transformers[i] == null) { throw new IllegalArgumentException("The transformer array must not contain a null transformer, index " + i + " was null"); } } } } collections-generic-4.01/src/java/org/apache/commons/collections15/functors/ChainedClosure.java0000644000175000017500000001100210464140763033050 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.functors; import org.apache.commons.collections15.Closure; import java.io.Serializable; import java.util.Collection; import java.util.Iterator; /** * Closure implementation that chains the specified closures together. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:24 $ * @since Commons Collections 3.0 */ public class ChainedClosure implements Closure, Serializable { /** * Serial version UID */ static final long serialVersionUID = -3520677225766901240L; /** * The closures to call in turn */ private final Closure[] iClosures; /** * Factory method that performs validation and copies the parameter array. * * @param closures the closures to chain, copied, no nulls * @return the chained closure * @throws IllegalArgumentException if the closures array is null * @throws IllegalArgumentException if any closure in the array is null */ public static Closure getInstance(Closure[] closures) { FunctorUtils.validate(closures); if (closures.length == 0) { return NOPClosure.INSTANCE; } closures = FunctorUtils.copy(closures); return new ChainedClosure(closures); } /** * Create a new Closure that calls each closure in turn, passing the * result into the next closure. The ordering is that of the iterator() * method on the collection. * * @param closures a collection of closures to chain * @return the chained closure * @throws IllegalArgumentException if the closures collection is null * @throws IllegalArgumentException if any closure in the collection is null */ public static Closure getInstance(Collection closures) { if (closures == null) { throw new IllegalArgumentException("Closure collection must not be null"); } if (closures.size() == 0) { return NOPClosure.INSTANCE; } // convert to array like this to guarantee iterator() ordering Closure[] cmds = new Closure[closures.size()]; int i = 0; for (Iterator it = closures.iterator(); it.hasNext();) { cmds[i++] = (Closure) it.next(); } FunctorUtils.validate(cmds); return new ChainedClosure(cmds); } /** * Factory method that performs validation. * * @param closure1 the first closure, not null * @param closure2 the second closure, not null * @return the chained closure * @throws IllegalArgumentException if either closure is null */ public static Closure getInstance(Closure closure1, Closure closure2) { if (closure1 == null || closure2 == null) { throw new IllegalArgumentException("Closures must not be null"); } Closure[] closures = new Closure[]{closure1, closure2}; return new ChainedClosure(closures); } /** * Constructor that performs no validation. * Use getInstance if you want that. * * @param closures the closures to chain, not copied, no nulls */ public ChainedClosure(Closure[] closures) { super(); iClosures = closures; } /** * Execute a list of closures. * * @param input the input object passed to each closure */ public void execute(T input) { for (int i = 0; i < iClosures.length; i++) { iClosures[i].execute(input); } } /** * Gets the closures, do not modify the array. * * @return the closures * @since Commons Collections 3.1 */ public Closure[] getClosures() { return iClosures; } } collections-generic-4.01/src/java/org/apache/commons/collections15/functors/ExceptionClosure.java0000644000175000017500000000362710464140757033474 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.functors; import org.apache.commons.collections15.Closure; import org.apache.commons.collections15.FunctorException; import java.io.Serializable; /** * Closure implementation that always throws an exception. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:24 $ * @since Commons Collections 3.0 */ public final class ExceptionClosure implements Closure, Serializable { /** * Serial version UID */ static final long serialVersionUID = 7179106032121985545L; /** * Singleton predicate instance */ public static final Closure INSTANCE = new ExceptionClosure(); /** * Factory returning the singleton instance. * * @return the singleton instance * @since Commons Collections 3.1 */ public static Closure getInstance() { return INSTANCE; } /** * Restricted constructor. */ private ExceptionClosure() { super(); } /** * Always throw an exception. * * @param input the input object * @throws FunctorException always */ public void execute(T input) { throw new FunctorException("ExceptionClosure invoked"); } } collections-generic-4.01/src/java/org/apache/commons/collections15/functors/package.html0000644000175000017500000000205610464140762031606 0ustar giovannigiovanni

          This package contains implementations of the {@link org.apache.commons.collections.Closure Closure}, {@link org.apache.commons.collections.Predicate Predicate}, {@link org.apache.commons.collections.Predicate Transformer} and {@link org.apache.commons.collections.Predicate Factory} interfaces. These provide simple callbacks for processing with collections. collections-generic-4.01/src/java/org/apache/commons/collections15/functors/IfClosure.java0000644000175000017500000000750610464140765032073 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.functors; import org.apache.commons.collections15.Closure; import org.apache.commons.collections15.Predicate; import java.io.Serializable; /** * Closure implementation acts as an if statement calling one or other closure * based on a predicate. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:24 $ * @since Commons Collections 3.0 */ public class IfClosure implements Closure, Serializable { /** * Serial version UID */ static final long serialVersionUID = 3518477308466486130L; /** * The test */ private final Predicate iPredicate; /** * The closure to use if true */ private final Closure iTrueClosure; /** * The closure to use if false */ private final Closure iFalseClosure; /** * Factory method that performs validation. * * @param predicate predicate to switch on * @param trueClosure closure used if true * @param falseClosure closure used if false * @return the if closure * @throws IllegalArgumentException if any argument is null */ public static Closure getInstance(Predicate predicate, Closure trueClosure, Closure falseClosure) { if (predicate == null) { throw new IllegalArgumentException("Predicate must not be null"); } if (trueClosure == null || falseClosure == null) { throw new IllegalArgumentException("Closures must not be null"); } return new IfClosure(predicate, trueClosure, falseClosure); } /** * Constructor that performs no validation. * Use getInstance if you want that. * * @param predicate predicate to switch on, not null * @param trueClosure closure used if true, not null * @param falseClosure closure used if false, not null */ public IfClosure(Predicate predicate, Closure trueClosure, Closure falseClosure) { super(); iPredicate = predicate; iTrueClosure = trueClosure; iFalseClosure = falseClosure; } /** * Executes the true or false closure accoring to the result of the predicate. * * @param input the input object */ public void execute(T input) { if (iPredicate.evaluate(input) == true) { iTrueClosure.execute(input); } else { iFalseClosure.execute(input); } } /** * Gets the predicate. * * @return the predicate * @since Commons Collections 3.1 */ public Predicate getPredicate() { return iPredicate; } /** * Gets the closure called when true. * * @return the closure * @since Commons Collections 3.1 */ public Closure getTrueClosure() { return iTrueClosure; } /** * Gets the closure called when false. * * @return the closure * @since Commons Collections 3.1 */ public Closure getFalseClosure() { return iFalseClosure; } } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootcollections-generic-4.01/src/java/org/apache/commons/collections15/functors/ExceptionTransformer.javacollections-generic-4.01/src/java/org/apache/commons/collections15/functors/ExceptionTransformer.jav0000644000175000017500000000377010464140761034213 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.functors; import org.apache.commons.collections15.FunctorException; import org.apache.commons.collections15.Transformer; import java.io.Serializable; /** * Transformer implementation that always throws an exception. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:24 $ * @since Commons Collections 3.0 */ public final class ExceptionTransformer implements Transformer, Serializable { /** * Serial version UID */ static final long serialVersionUID = 7179106032121985545L; /** * Singleton predicate instance */ public static final Transformer INSTANCE = new ExceptionTransformer(); /** * Factory returning the singleton instance. * * @return the singleton instance * @since Commons Collections 3.1 */ public static Transformer getInstance() { return INSTANCE; } /** * Restricted constructor. */ private ExceptionTransformer() { super(); } /** * Transforms the input to result by cloning it. * * @param input the input object to transform * @return never * @throws FunctorException always */ public O transform(I input) { throw new FunctorException("ExceptionTransformer invoked"); } } collections-generic-4.01/src/java/org/apache/commons/collections15/functors/InstanceofPredicate.java0000644000175000017500000000516510464140762034106 0ustar giovannigiovanni// GenericsNote: Converted, although perhaps this should not be templated. Not sure! /* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.functors; import org.apache.commons.collections15.Predicate; import java.io.Serializable; /** * Predicate implementation that returns true if the input is an instanceof * the type stored in this predicate. * * Since this predicate operates on the type of the objects passed to it, generics are not used. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:24 $ * @since Commons Collections 3.0 */ public final class InstanceofPredicate implements Predicate, Serializable { /** * Serial version UID */ static final long serialVersionUID = -6682656911025165584L; /** * The type to compare to */ private final Class iType; /** * Factory to create the identity predicate. * * @param type the type to check for, may not be null * @return the predicate * @throws IllegalArgumentException if the class is null */ public static Predicate getInstance(Class type) { if (type == null) { throw new IllegalArgumentException("The type to check instanceof must not be null"); } return new InstanceofPredicate(type); } /** * Constructor that performs no validation. * Use getInstance if you want that. * * @param type the type to check for */ public InstanceofPredicate(Class type) { super(); iType = type; } /** * Evaluates the predicate returning true if the input object is of the correct type. * * @param object the input object * @return true if input is of stored type */ public boolean evaluate(Object object) { return (iType.isInstance(object)); } /** * Gets the type to compare to. * * @return the type * @since Commons Collections 3.1 */ public Class getType() { return iType; } } collections-generic-4.01/src/java/org/apache/commons/collections15/functors/SwitchClosure.java0000644000175000017500000001503210464140765032767 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.functors; import org.apache.commons.collections15.Closure; import org.apache.commons.collections15.Predicate; import java.io.Serializable; import java.util.Iterator; import java.util.Map; /** * Closure implementation calls the closure whose predicate returns true, * like a switch statement. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:24 $ * @since Commons Collections 3.0 */ public class SwitchClosure implements Closure, Serializable { /** * Serial version UID */ static final long serialVersionUID = 3518477308466486130L; /** * The tests to consider */ private final Predicate[] iPredicates; /** * The matching closures to call */ private final Closure[] iClosures; /** * The default closure to call if no tests match */ private final Closure iDefault; /** * Factory method that performs validation and copies the parameter arrays. * * @param predicates array of predicates, cloned, no nulls * @param closures matching array of closures, cloned, no nulls * @param defaultClosure the closure to use if no match, null means nop * @return the chained closure * @throws IllegalArgumentException if array is null * @throws IllegalArgumentException if any element in the array is null */ public static Closure getInstance(Predicate[] predicates, Closure[] closures, Closure defaultClosure) { FunctorUtils.validate(predicates); FunctorUtils.validate(closures); if (predicates.length != closures.length) { throw new IllegalArgumentException("The predicate and closure arrays must be the same size"); } if (predicates.length == 0) { return (defaultClosure == null ? NOPClosure.INSTANCE : defaultClosure); } predicates = FunctorUtils.copy(predicates); closures = FunctorUtils.copy(closures); return new SwitchClosure(predicates, closures, defaultClosure); } /** * Create a new Closure that calls one of the closures depending * on the predicates. *

          * The Map consists of Predicate keys and Closure values. A closure * is called if its matching predicate returns true. Each predicate is evaluated * until one returns true. If no predicates evaluate to true, the default * closure is called. The default closure is set in the map with a * null key. The ordering is that of the iterator() method on the entryset * collection of the map. * * @param predicatesAndClosures a map of predicates to closures * @return the switch closure * @throws IllegalArgumentException if the map is null * @throws IllegalArgumentException if any closure in the map is null * @throws ClassCastException if the map elements are of the wrong type */ public static Closure getInstance(Map, Closure> predicatesAndClosures) { Closure[] closures = null; Predicate[] preds = null; if (predicatesAndClosures == null) { throw new IllegalArgumentException("The predicate and closure map must not be null"); } if (predicatesAndClosures.size() == 0) { return NOPClosure.INSTANCE; } // convert to array like this to guarantee iterator() ordering Closure defaultClosure = (Closure) predicatesAndClosures.remove(null); int size = predicatesAndClosures.size(); if (size == 0) { return (defaultClosure == null ? NOPClosure.INSTANCE : defaultClosure); } closures = new Closure[size]; preds = new Predicate[size]; int i = 0; for (Iterator it = predicatesAndClosures.entrySet().iterator(); it.hasNext();) { Map.Entry entry = (Map.Entry) it.next(); preds[i] = (Predicate) entry.getKey(); closures[i] = (Closure) entry.getValue(); i++; } return new SwitchClosure(preds, closures, defaultClosure); } /** * Constructor that performs no validation. * Use getInstance if you want that. * * @param predicates array of predicates, not cloned, no nulls * @param closures matching array of closures, not cloned, no nulls * @param defaultClosure the closure to use if no match, null means nop */ public SwitchClosure(Predicate[] predicates, Closure[] closures, Closure defaultClosure) { super(); iPredicates = predicates; iClosures = closures; iDefault = (defaultClosure == null ? NOPClosure.INSTANCE : defaultClosure); } /** * Executes the closure whose matching predicate returns true * * @param input the input object */ public void execute(T input) { for (int i = 0; i < iPredicates.length; i++) { if (iPredicates[i].evaluate(input) == true) { iClosures[i].execute(input); return; } } iDefault.execute(input); } /** * Gets the predicates, do not modify the array. * * @return the predicates * @since Commons Collections 3.1 */ public Predicate[] getPredicates() { return iPredicates; } /** * Gets the closures, do not modify the array. * * @return the closures * @since Commons Collections 3.1 */ public Closure[] getClosures() { return iClosures; } /** * Gets the default closure. * * @return the default closure * @since Commons Collections 3.1 */ public Closure getDefaultClosure() { return iDefault; } } collections-generic-4.01/src/java/org/apache/commons/collections15/functors/ClosureTransformer.java0000644000175000017500000000504610464140765034034 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.functors; import org.apache.commons.collections15.Closure; import org.apache.commons.collections15.Transformer; import java.io.Serializable; /** * Transformer implementation that calls a Closure using the input object * and then returns the input. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:24 $ * @since Commons Collections 3.0 */ public class ClosureTransformer implements Transformer, Serializable { /** * Serial version UID */ static final long serialVersionUID = 478466901448617286L; /** * The closure to wrap */ private final Closure iClosure; /** * Factory method that performs validation. * * @param closure the closure to call, not null * @return the closure transformer * @throws IllegalArgumentException if the closure is null */ public static Transformer getInstance(Closure closure) { if (closure == null) { throw new IllegalArgumentException("Closure must not be null"); } return new ClosureTransformer(closure); } /** * Constructor that performs no validation. * Use getInstance if you want that. * * @param closure the closure to call, not null */ public ClosureTransformer(Closure closure) { super(); iClosure = closure; } /** * Transforms the input to result by executing a closure. * * @param input the input object to transform * @return the transformed result */ public T transform(T input) { iClosure.execute(input); return input; } /** * Gets the closure. * * @return the closure * @since Commons Collections 3.1 */ public Closure getClosure() { return iClosure; } } collections-generic-4.01/src/java/org/apache/commons/collections15/functors/AllPredicate.java0000644000175000017500000000706710464140761032527 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.functors; import org.apache.commons.collections15.Predicate; import java.io.Serializable; import java.util.Collection; /** * Predicate implementation that returns true if all the predicates return true. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:24 $ * @since Commons Collections 3.0 */ public final class AllPredicate implements Predicate, PredicateDecorator, Serializable { /** * Serial version UID */ static final long serialVersionUID = -3094696765038308799L; /** * The array of predicates to call */ private final Predicate[] iPredicates; /** * Factory to create the predicate. * * @param predicates the predicates to check, cloned, not null * @return the all predicate * @throws IllegalArgumentException if the predicates array is null * @throws IllegalArgumentException if the predicates array has less than 2 elements * @throws IllegalArgumentException if any predicate in the array is null */ public static Predicate getInstance(Predicate[] predicates) { FunctorUtils.validateMin2(predicates); predicates = FunctorUtils.copy(predicates); return new AllPredicate(predicates); } /** * Factory to create the predicate. * * @param predicates the predicates to check, cloned, not null * @return the all predicate * @throws IllegalArgumentException if the predicates array is null * @throws IllegalArgumentException if any predicate in the array is null * @throws IllegalArgumentException if the predicates array has less than 2 elements */ public static Predicate getInstance(Collection> predicates) { Predicate[] preds = FunctorUtils.validate(predicates); return new AllPredicate(preds); } /** * Constructor that performs no validation. * Use getInstance if you want that. * * @param predicates the predicates to check, not cloned, not null */ public AllPredicate(Predicate[] predicates) { super(); iPredicates = predicates; } /** * Evaluates the predicate returning true if all predicates return true. * * @param object the input object * @return true if all decorated predicates return true */ public boolean evaluate(T object) { for (int i = 0; i < iPredicates.length; i++) { if (iPredicates[i].evaluate(object) == false) { return false; } } return true; } /** * Gets the predicates, do not modify the array. * * @return the predicates * @since Commons Collections 3.1 */ public Predicate[] getPredicates() { return iPredicates; } } collections-generic-4.01/src/java/org/apache/commons/collections15/functors/ExceptionFactory.java0000644000175000017500000000357510464140764033467 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.functors; import org.apache.commons.collections15.Factory; import org.apache.commons.collections15.FunctorException; import java.io.Serializable; /** * Factory implementation that always throws an exception. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:24 $ * @since Commons Collections 3.0 */ public final class ExceptionFactory implements Factory, Serializable { /** * Serial version UID */ static final long serialVersionUID = 7179106032121985545L; /** * Singleton predicate instance */ public static final Factory INSTANCE = new ExceptionFactory(); /** * Factory returning the singleton instance. * * @return the singleton instance * @since Commons Collections 3.1 */ public static Factory getInstance() { return INSTANCE; } /** * Restricted constructor. */ private ExceptionFactory() { super(); } /** * Always throws an exception. * * @return never * @throws FunctorException always */ public T create() { throw new FunctorException("ExceptionFactory invoked"); } } ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootcollections-generic-4.01/src/java/org/apache/commons/collections15/functors/InstantiateTransformer.javacollections-generic-4.01/src/java/org/apache/commons/collections15/functors/InstantiateTransformer.j0000644000175000017500000001010010464140756034176 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.functors; import org.apache.commons.collections15.FunctorException; import org.apache.commons.collections15.Transformer; import java.io.Serializable; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; /** * Transformer implementation that creates a new object instance by reflection. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:24 $ * @since Commons Collections 3.0 */ public class InstantiateTransformer implements Transformer, Serializable { /** * The serial version */ static final long serialVersionUID = 3786388740793356347L; /** * Singleton instance that uses the no arg constructor */ public static final InstantiateTransformer NO_ARG_INSTANCE = new InstantiateTransformer(); /** * The constructor parameter types */ private final Class[] iParamTypes; /** * The constructor arguments */ private final Object[] iArgs; /** * Transformer method that performs validation. * * @param paramTypes the constructor parameter types * @param args the constructor arguments * @return an instantiate transformer */ public static InstantiateTransformer getInstance(Class[] paramTypes, Object[] args) { if (((paramTypes == null) && (args != null)) || ((paramTypes != null) && (args == null)) || ((paramTypes != null) && (args != null) && (paramTypes.length != args.length))) { throw new IllegalArgumentException("Parameter types must match the arguments"); } if (paramTypes == null || paramTypes.length == 0) { return NO_ARG_INSTANCE; } else { paramTypes = (Class[]) paramTypes.clone(); args = (Object[]) args.clone(); } return new InstantiateTransformer(paramTypes, args); } /** * Constructor for no arg instance. */ private InstantiateTransformer() { super(); iParamTypes = null; iArgs = null; } /** * Constructor that performs no validation. * Use getInstance if you want that. * * @param paramTypes the constructor parameter types, not cloned * @param args the constructor arguments, not cloned */ public InstantiateTransformer(Class[] paramTypes, Object[] args) { super(); iParamTypes = paramTypes; iArgs = args; } /** * Transforms the input Class object to a result by instantiation. * * @param input the input object to transform * @return the transformed result */ public Object transform(Class input) { try { Constructor con = ((Class) input).getConstructor(iParamTypes); return con.newInstance(iArgs); } catch (NoSuchMethodException ex) { throw new FunctorException("InstantiateTransformer: The constructor must exist and be public "); } catch (InstantiationException ex) { throw new FunctorException("InstantiateTransformer: InstantiationException", ex); } catch (IllegalAccessException ex) { throw new FunctorException("InstantiateTransformer: Constructor must be public", ex); } catch (InvocationTargetException ex) { throw new FunctorException("InstantiateTransformer: Constructor threw an exception", ex); } } } collections-generic-4.01/src/java/org/apache/commons/collections15/MultiMap.java0000644000175000017500000003516610464140760030063 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15; import java.util.*; /** * Defines a map that holds a collection of values against each key. *

          * A MultiMap is a Map with slightly different semantics. * Putting a value into the map will add the value to a Collection at that key. * Getting a value will return a Collection, holding all the values put to that key. *

          * For example: *

           * Number key = new Integer(5);
           * MultiMap<Number,String> mhm = new MultiHashMap<Number,String>();
           * mhm.put(key, "A");
           * mhm.put(key, "B");
           * mhm.put(key, "C");
           * Collection<String> coll = mhm.get(key);
          *

          * coll will be a collection containing "A", "B", "C". *

          * NOTE: Note: this new, generics-friendly version of the MultiMap interface does * NOT extend java.util.Map! This is because MultiMap breaks the Map contract in * too many ways to allow generics support. However, you can get a live java.util.Map * for a MultiMap with the method {@link #map()}. * * @author Christopher Berry * @author James Strachan * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:19 $ * @since Commons Collections 2.0 */ public interface MultiMap { /** * Removes a specific value from map. *

          * The item is removed from the collection mapped to the specified key. * Other values attached to that key are unaffected. *

          * If the last value for a key is removed, implementations typically * return null from a subsequant get(Object), however * they may choose to return an empty collection. * * @param key the key to remove from * @param item the item to remove * @return the value removed (which was passed in), null if nothing removed * @throws UnsupportedOperationException if the map is unmodifiable * @throws ClassCastException if the key or value is of an invalid type * @throws NullPointerException if the key or value is null and null is invalid */ public V remove(Object key, Object item); /** * Gets the number of values in this map for the given key. *

          * Implementations return the count of keys in the map, or 0 if there are no values for the given key. * * @return the number of values in this map for the given key. */ int size(Object key); //----------------------------------------------------------------------- /** * Gets the number of keys in this map. *

          * Implementations return the count of keys in the map. * * @return the number of key-collection mappings in this map */ int size(); /** * Gets the collection of values associated with the specified key. *

          * The returned value will implement Collection. Implementations * are free to declare that they return Collection subclasses * such as List or Set. *

          * Implementations return null if no values have * been mapped to the key. *

          * Implementations may choose to return a clone of the internal collection. * * @param key the key to retrieve * @return the Collection of values, implementations should * return null for no mapping, but may return an empty collection * @throws ClassCastException if the key is of an invalid type * @throws NullPointerException if the key is null and null keys are invalid */ Collection get(Object key); /** * Checks whether the map contains the value specified. *

          * Implementations check all collections15 against all keys for the value. * * @param value the value to search for * @return true if the map contains the value * @throws ClassCastException if the value is of an invalid type * @throws NullPointerException if the value is null and null value are invalid */ boolean containsValue(Object value); /** * Checks whether the map contains the value specified, at the key specified. * * @param value the value to search for * @param key the key against which to search for the value * @return true if the map contains the value * @throws ClassCastException if the value is of an invalid type * @throws NullPointerException if the value is null and null value are invalid */ boolean containsValue(Object key, Object value); /** * Adds the value to the collection associated with the specified key. *

          * Unlike a normal Map the previous value is not replaced. * Instead the new value is added to the collection stored against the key. * The collection may be a List, Set or other * collection dependent on implementation. * * @param key the key to store against * @param value the value to add to the collection at the key * @return typically the value added if the map changed and null if the map did not change * @throws UnsupportedOperationException if the map is unmodifiable * @throws ClassCastException if the key or value is of an invalid type * @throws NullPointerException if the key or value is null and null is invalid * @throws IllegalArgumentException if the key or value is invalid */ V put(K key, V value); /** * Removes all values associated with the specified key. *

          * Implementations typically return null from a subsequent * get(Object), however they may choose to return an empty collection. * * @param key the key to remove values from * @return the Collection of values removed, implementations should * return null for no mapping found, but may return an empty collection * @throws UnsupportedOperationException if the map is unmodifiable * @throws ClassCastException if the key is of an invalid type * @throws NullPointerException if the key is null and null keys are invalid */ Collection remove(Object key); /** * Gets a collection containing all the values in the map. *

          * Inplementations return a collection containing the combination * of values from all keys. * * @return a collection view of the values contained in this map */ Collection values(); /** * Returns true if this map contains no key-value mappings. * * @return true if this map contains no key-value mappings. */ boolean isEmpty(); /** * Returns true if this map contains a mapping for the specified * key. More formally, returns true if and only if * this map contains a mapping for a key k such that * (key==null ? k==null : key.equals(k)). (There can be * at most one such mapping.) * * @param key key whose presence in this map is to be tested. * @return true if this map contains a mapping for the specified * key. * @throws ClassCastException if the key is of an inappropriate type for * this map (optional). * @throws NullPointerException if the key is null and this map * does not permit null keys (optional). */ boolean containsKey(Object key); // Modification Operations // Bulk Operations /** * Copies all of the mappings from the specified map to this map * (optional operation). The effect of this call is equivalent to that * of calling {@link #put(Object,Object) put(k, v)} on this map once * for each mapping from key k to value v in the * specified map. The behavior of this operation is unspecified if the * specified map is modified while the operation is in progress. * * @param t Mappings to be stored in this map. * @throws UnsupportedOperationException if the putAll method is * not supported by this map. * @throws ClassCastException if the class of a key or value in the * specified map prevents it from being stored in this map. * @throws IllegalArgumentException some aspect of a key or value in the * specified map prevents it from being stored in this map. * @throws NullPointerException if the specified map is null, or if * this map does not permit null keys or values, and the * specified map contains null keys or values. */ void putAll(Map t); /** * Copies all of the mappings from the specified multimap to this multimap * (optional operation). The effect of this call is equivalent to that * of calling {@link #put(Object,Object) put(k, v)} on this map once * for each mapping from key to collections15 of values in the * specified multimap. The behavior of this operation is unspecified if the * specified multimap is modified while the operation is in progress. * * @param t Mappings to be stored in this map. * @throws UnsupportedOperationException if the putAll method is * not supported by this map. * @throws ClassCastException if the class of a key or value in the * specified map prevents it from being stored in this map. * @throws IllegalArgumentException some aspect of a key or value in the * specified map prevents it from being stored in this map. * @throws NullPointerException if the specified map is null, or if * this map does not permit null keys or values, and the * specified map contains null keys or values. */ void putAll(MultiMap t); /** * Copies all of the values in the given collection in to the multimap against the given key. * @param key the key against which to store the values. * @param values the collection of values to map to the key. */ boolean putAll(K key, Collection values); Iterator iterator(Object key); /** * Removes all mappings from this map (optional operation). * * @throws UnsupportedOperationException clear is not supported by this * map. */ void clear(); // Views /** * Returns a set view of the keys contained in this map. The set is * backed by the map, so changes to the map are reflected in the set, and * vice-versa. If the map is modified while an iteration over the set is * in progress (except through the iterator's own remove * operation), the results of the iteration are undefined. The set * supports element removal, which removes the corresponding mapping from * the map, via the Iterator.remove, Set.remove, * removeAll retainAll, and clear operations. * It does not support the add or addAll operations. * * @return a set view of the keys contained in this map. */ Set keySet(); /** * Returns a set view of the mappings contained in this map. Each element * in the returned set is a {@link Map.Entry}. The set is backed by the * map, so changes to the map are reflected in the set, and vice-versa. * If the map is modified while an iteration over the set is in progress * (except through the iterator's own remove operation, or through * the setValue operation on a map entry returned by the iterator) * the results of the iteration are undefined. The set supports element * removal, which removes the corresponding mapping from the map, via the * Iterator.remove, Set.remove, removeAll, * retainAll and clear operations. It does not support * the add or addAll operations. * * @return a set view of the mappings contained in this map. */ Set>> entrySet(); /** * Returns a java.util.Map<K,Collection<V>> for this MultiMap. * * @return the underlying java.util.Map for this MultiMap. */ Map> map(); // Comparison and hashing /** * Compares the specified object with this map for equality. Returns * true if the given object is also a map and the two Maps * represent the same mappings. More formally, two maps t1 and * t2 represent the same mappings if * t1.entrySet().equals(t2.entrySet()). This ensures that the * equals method works properly across different implementations * of the Map interface. * * @param o object to be compared for equality with this map. * @return true if the specified object is equal to this map. */ boolean equals(Object o); /** * Returns the hash code value for this map. The hash code of a map * is defined to be the sum of the hashCodes of each entry in the map's * entrySet view. This ensures that t1.equals(t2) implies * that t1.hashCode()==t2.hashCode() for any two maps * t1 and t2, as required by the general * contract of Object.hashCode. * * @return the hash code value for this map. * @see Map.Entry#hashCode() * @see Object#hashCode() * @see Object#equals(Object) * @see #equals(Object) */ int hashCode(); } collections-generic-4.01/src/java/org/apache/commons/collections15/SortedBidiMap.java0000644000175000017500000000523310464140755031015 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15; import java.util.SortedMap; /** * Defines a map that allows bidirectional lookup between key and values * and retains both keys and values in sorted order. *

          * Implementations should allow a value to be looked up from a key and * a key to be looked up from a value with equal performance. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:19 $ * @since Commons Collections 3.0 */ public interface SortedBidiMap extends OrderedBidiMap, SortedMap { /** * Gets a view of this map where the keys and values are reversed. *

          * Changes to one map will be visible in the other and vice versa. * This enables both directions of the map to be accessed equally. *

          * Implementations should seek to avoid creating a new object every time this * method is called. See AbstractMap.values() etc. Calling this * method on the inverse map should return the original. *

          * Implementations must return a SortedBidiMap instance, * usually by forwarding to inverseSortedBidiMap(). * * @return an inverted bidirectional map */ public BidiMap inverseBidiMap(); /** * Gets a view of this map where the keys and values are reversed. *

          * Changes to one map will be visible in the other and vice versa. * This enables both directions of the map to be accessed as a SortedMap. *

          * Implementations should seek to avoid creating a new object every time this * method is called. See AbstractMap.values() etc. Calling this * method on the inverse map should return the original. *

          * The inverse map returned by inverseBidiMap() should be the * same object as returned by this method. * * @return an inverted bidirectional map */ public SortedBidiMap inverseSortedBidiMap(); } collections-generic-4.01/src/java/org/apache/commons/collections15/keyvalue/0000755000175000017500000000000011664401370027302 5ustar giovannigiovannicollections-generic-4.01/src/java/org/apache/commons/collections15/keyvalue/MultiKey.java0000644000175000017500000001415610464140757031725 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.keyvalue; import java.io.Serializable; import java.util.Arrays; /** * A MultiKey allows multiple map keys to be merged together. *

          * The purpose of this class is to avoid the need to write code to handle * maps of maps. An example might be the need to lookup a filename by * key and locale. The typical solution might be nested maps. This class * can be used instead by creating an instance passing in the key and locale. *

          * Example usage: *

           * // populate map with data mapping key+locale to localizedText
           * Map map = new HashMap();
           * MultiKey multiKey = new MultiKey(key, locale);
           * map.put(multiKey, localizedText);
           * 

          * // later retireve the localized text * MultiKey multiKey = new MultiKey(key, locale); * String localizedText = (String) map.get(multiKey); *

          * * @author Howard Lewis Ship * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:32 $ * @since Commons Collections 3.0 */ public class MultiKey implements Serializable { // This class could implement List, but that would confuse it's purpose /** * Serialisation version */ private static final long serialVersionUID = 4465448607415788805L; /** * The individual keys */ private final K[] keys; /** * The cached hashCode */ private final int hashCode; /** * Constructor taking two keys. *

          * The keys should be immutable * If they are not then they must not be changed after adding to the MultiKey. * * @param keys the keys */ public MultiKey(K... keys) { this(keys, true); } /** * Constructor taking an array of keys, optionally choosing whether to clone. *

          * If the array is not cloned, then it must not be modified. *

          * This method is public for performance reasons only, to avoid a clone. * The hashcode is calculated once here in this method. * Therefore, changing the array passed in would not change the hashcode but * would change the equals method, which is a bug. *

          * This is the only fully safe usage of this constructor, as the object array * is never made available in a variable: *

               * new MultiKey(new Object[] {...}, false);
               * 
          *

          * The keys should be immutable * If they are not then they must not be changed after adding to the MultiKey. * * @param keys the array of keys, not null * @param makeClone true to clone the array, false to assign it * @throws IllegalArgumentException if the key array is null * @since Commons Collections 3.1 */ public MultiKey(K[] keys, boolean makeClone) { super(); if (keys == null) { throw new IllegalArgumentException("The array of keys must not be null"); } if (makeClone) { this.keys = (K[]) keys.clone(); } else { this.keys = keys; } int total = 0; for (int i = 0; i < keys.length; i++) { if (keys[i] != null) { total ^= keys[i].hashCode(); } } hashCode = total; } //----------------------------------------------------------------------- /** * Gets a clone of the array of keys. *

          * The keys should be immutable * If they are not then they must not be changed. * * @return the individual keys */ public K[] getKeys() { return keys.clone(); } /** * Gets the key at the specified index. *

          * The key should be immutable. * If it is not then it must not be changed. * * @param index the index to retrieve * @return the key at the index * @throws IndexOutOfBoundsException if the index is invalid * @since Commons Collections 3.1 */ public K getKey(int index) { return keys[index]; } /** * Gets the size of the list of keys. * * @return the size of the list of keys * @since Commons Collections 3.1 */ public int size() { return keys.length; } //----------------------------------------------------------------------- /** * Compares this object to another. *

          * To be equal, the other object must be a MultiKey with the * same number of keys which are also equal. * * @param other the other object to compare to * @return true if equal */ public boolean equals(Object other) { if (other == this) { return true; } if (other instanceof MultiKey) { MultiKey otherMulti = (MultiKey) other; return Arrays.equals(keys, otherMulti.keys); } return false; } /** * Gets the combined hash code that is computed from all the keys. *

          * This value is computed once and then cached, so elements should not * change their hash codes once created (note that this is the same * constraint that would be used if the individual keys elements were * themselves {@link java.util.Map Map} keys. * * @return the hash code */ public int hashCode() { return hashCode; } /** * Gets a debugging string version of the key. * * @return a debugging string */ public String toString() { return "MultiKey" + Arrays.asList(keys).toString(); } } collections-generic-4.01/src/java/org/apache/commons/collections15/keyvalue/DefaultMapEntry.java0000644000175000017500000000411610464140757033221 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.keyvalue; import org.apache.commons.collections15.KeyValue; import java.util.Map; /** * A restricted implementation of {@link java.util.Map.Entry} that prevents * the MapEntry contract from being broken. * * @author James Strachan * @author Michael A. Smith * @author Neil O'Toole * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:32 $ * @since Commons Collections 3.0 */ public final class DefaultMapEntry extends AbstractMapEntry { /** * Constructs a new entry with the specified key and given value. * * @param key the key for the entry, may be null * @param value the value for the entry, may be null */ public DefaultMapEntry(final K key, final V value) { super(key, value); } /** * Constructs a new entry from the specified KeyValue. * * @param pair the pair to copy, must not be null * @throws NullPointerException if the entry is null */ public DefaultMapEntry(final KeyValue pair) { super(pair.getKey(), pair.getValue()); } /** * Constructs a new entry from the specified MapEntry. * * @param entry the entry to copy, must not be null * @throws NullPointerException if the entry is null */ public DefaultMapEntry(final Map.Entry entry) { super(entry.getKey(), entry.getValue()); } } collections-generic-4.01/src/java/org/apache/commons/collections15/keyvalue/DefaultKeyValue.java0000644000175000017500000001136610464140756033213 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.keyvalue; import org.apache.commons.collections15.KeyValue; import java.util.Map; /** * A mutable KeyValue pair that does not implement MapEntry. *

          * Note that a DefaultKeyValue instance may not contain * itself as a key or value. * * @author James Strachan * @author Michael A. Smith * @author Neil O'Toole * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:32 $ * @since Commons Collections 3.0 */ public class DefaultKeyValue extends AbstractKeyValue { /** * Constructs a new pair with a null key and null value. */ public DefaultKeyValue() { super(null, null); } /** * Constructs a new pair with the specified key and given value. * * @param key the key for the entry, may be null * @param value the value for the entry, may be null */ public DefaultKeyValue(final K key, final V value) { super(key, value); } /** * Constructs a new pair from the specified KeyValue. * * @param pair the pair to copy, must not be null * @throws NullPointerException if the entry is null */ public DefaultKeyValue(final KeyValue pair) { super(pair.getKey(), pair.getValue()); } /** * Constructs a new pair from the specified MapEntry. * * @param entry the entry to copy, must not be null * @throws NullPointerException if the entry is null */ public DefaultKeyValue(final Map.Entry entry) { super(entry.getKey(), entry.getValue()); } //----------------------------------------------------------------------- /** * Sets the key. * * @param key the new key * @return the old key * @throws IllegalArgumentException if key is this object */ public K setKey(final K key) { if ((Object) key == this) { throw new IllegalArgumentException("DefaultKeyValue may not contain itself as a key."); } final K old = this.key; this.key = key; return old; } /** * Sets the value. * * @param value the new value * @return the old value of the value * @throws IllegalArgumentException if value is this object */ public V setValue(final V value) { if ((Object) value == this) { throw new IllegalArgumentException("DefaultKeyValue may not contain itself as a value."); } final V old = this.value; this.value = value; return old; } //----------------------------------------------------------------------- /** * Returns a new Map.Entry object with key and value from this pair. * * @return a MapEntry instance */ public Map.Entry toMapEntry() { return new DefaultMapEntry(this); } //----------------------------------------------------------------------- /** * Compares this Map Entry with another Map Entry. *

          * Returns true if the compared object is also a DefaultKeyValue, * and its key and value are equal to this object's key and value. * * @param obj the object to compare to * @return true if equal key and value */ public boolean equals(final Object obj) { if (obj == this) { return true; } if (obj instanceof DefaultKeyValue == false) { return false; } DefaultKeyValue other = (DefaultKeyValue) obj; return (getKey() == null ? other.getKey() == null : getKey().equals(other.getKey())) && (getValue() == null ? other.getValue() == null : getValue().equals(other.getValue())); } /** * Gets a hashCode compatible with the equals method. *

          * Implemented per API documentation of {@link java.util.Map.Entry#hashCode()}, * however subclasses may override this. * * @return a suitable hash code */ public int hashCode() { return (getKey() == null ? 0 : getKey().hashCode()) ^ (getValue() == null ? 0 : getValue().hashCode()); } } collections-generic-4.01/src/java/org/apache/commons/collections15/keyvalue/TiedMapEntry.java0000644000175000017500000000745110464140762032523 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.keyvalue; import org.apache.commons.collections15.KeyValue; import java.io.Serializable; import java.util.Map; /** * A Map Entry tied to a map underneath. *

          * This can be used to enable a map entry to make changes on the underlying * map, however this will probably mess up any iterators. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:32 $ * @since Commons Collections 3.0 */ public class TiedMapEntry implements Map.Entry, KeyValue, Serializable { /** * Serialization version */ private static final long serialVersionUID = -8453869361373831205L; /** * The map underlying the entry/iterator */ private final Map map; /** * The key */ private final K key; /** * Constructs a new entry with the given Map and key. * * @param map the map * @param key the key */ public TiedMapEntry(Map map, K key) { super(); this.map = map; this.key = key; } // Map.Entry interface //------------------------------------------------------------------------- /** * Gets the key of this entry * * @return the key */ public K getKey() { return key; } /** * Gets the value of this entry direct from the map. * * @return the value */ public V getValue() { return map.get(key); } /** * Sets the value associated with the key direct onto the map. * * @param value the new value * @return the old value * @throws IllegalArgumentException if the value is set to this map entry */ public V setValue(V value) { if ((Object) value == this) { throw new IllegalArgumentException("Cannot set value to this map entry"); } return map.put(key, value); } /** * Compares this Map Entry with another Map Entry. *

          * Implemented per API documentation of {@link java.util.Map.Entry#equals(Object)} * * @param obj the object to compare to * @return true if equal key and value */ public boolean equals(Object obj) { if (obj == this) { return true; } if (obj instanceof Map.Entry == false) { return false; } Map.Entry other = (Map.Entry) obj; Object value = getValue(); return (key == null ? other.getKey() == null : key.equals(other.getKey())) && (value == null ? other.getValue() == null : value.equals(other.getValue())); } /** * Gets a hashCode compatible with the equals method. *

          * Implemented per API documentation of {@link java.util.Map.Entry#hashCode()} * * @return a suitable hash code */ public int hashCode() { Object value = getValue(); return (getKey() == null ? 0 : getKey().hashCode()) ^ (value == null ? 0 : value.hashCode()); } /** * Gets a string version of the entry. * * @return entry as a string */ public String toString() { return getKey() + "=" + getValue(); } } ././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootcollections-generic-4.01/src/java/org/apache/commons/collections15/keyvalue/AbstractMapEntryDecorator.javacollections-generic-4.01/src/java/org/apache/commons/collections15/keyvalue/AbstractMapEntryDecorato0000644000175000017500000000456110464140755034143 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.keyvalue; import org.apache.commons.collections15.KeyValue; import java.util.Map; /** * Provides a base decorator that allows additional functionality to be added * to a Map Entry. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:32 $ * @since Commons Collections 3.0 */ public abstract class AbstractMapEntryDecorator implements Map.Entry, KeyValue { /** * The Map.Entry to decorate */ protected final Map.Entry entry; /** * Constructor that wraps (not copies). * * @param entry the Map.Entry to decorate, must not be null * @throws IllegalArgumentException if the collection is null */ public AbstractMapEntryDecorator(Map.Entry entry) { if (entry == null) { throw new IllegalArgumentException("Map Entry must not be null"); } this.entry = entry; } /** * Gets the map being decorated. * * @return the decorated map */ protected Map.Entry getMapEntry() { return entry; } //----------------------------------------------------------------------- public K getKey() { return entry.getKey(); } public V getValue() { return entry.getValue(); } public V setValue(V object) { return entry.setValue(object); } public boolean equals(Object object) { if (object == this) { return true; } return entry.equals(object); } public int hashCode() { return entry.hashCode(); } public String toString() { return entry.toString(); } } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootcollections-generic-4.01/src/java/org/apache/commons/collections15/keyvalue/UnmodifiableMapEntry.javacollections-generic-4.01/src/java/org/apache/commons/collections15/keyvalue/UnmodifiableMapEntry.jav0000644000175000017500000000462210464140755034072 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.keyvalue; import org.apache.commons.collections15.KeyValue; import org.apache.commons.collections15.Unmodifiable; import java.util.Map; /** * A {@link java.util.Map.Entry} that throws UnsupportedOperationException * when setValue is called. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:32 $ * @since Commons Collections 3.0 */ public final class UnmodifiableMapEntry extends AbstractMapEntry implements Unmodifiable { /** * Constructs a new entry with the specified key and given value. * * @param key the key for the entry, may be null * @param value the value for the entry, may be null */ public UnmodifiableMapEntry(final K key, final V value) { super(key, value); } /** * Constructs a new entry from the specified KeyValue. * * @param pair the pair to copy, must not be null * @throws NullPointerException if the entry is null */ public UnmodifiableMapEntry(final KeyValue pair) { super(pair.getKey(), pair.getValue()); } /** * Constructs a new entry from the specified MapEntry. * * @param entry the entry to copy, must not be null * @throws NullPointerException if the entry is null */ public UnmodifiableMapEntry(final Map.Entry entry) { super(entry.getKey(), entry.getValue()); } /** * Throws UnsupportedOperationException. * * @param value the new value * @return the previous value * @throws UnsupportedOperationException always */ public V setValue(V value) { throw new UnsupportedOperationException("setValue() is not supported"); } } collections-generic-4.01/src/java/org/apache/commons/collections15/keyvalue/AbstractKeyValue.java0000644000175000017500000000410410464140760033355 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.keyvalue; import org.apache.commons.collections15.KeyValue; /** * Abstract pair class to assist with creating KeyValue and MapEntry implementations. * * @author James Strachan * @author Michael A. Smith * @author Neil O'Toole * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:32 $ * @since Commons Collections 3.0 */ public abstract class AbstractKeyValue implements KeyValue { /** * The key */ protected K key; /** * The value */ protected V value; /** * Constructs a new pair with the specified key and given value. * * @param key the key for the entry, may be null * @param value the value for the entry, may be null */ protected AbstractKeyValue(K key, V value) { super(); this.key = key; this.value = value; } /** * Gets the key from the pair. * * @return the key */ public K getKey() { return key; } /** * Gets the value from the pair. * * @return the value */ public V getValue() { return value; } /** * Gets a debugging String view of the pair. * * @return a String view of the entry */ public String toString() { return new StringBuffer().append(getKey()).append('=').append(getValue()).toString(); } } collections-generic-4.01/src/java/org/apache/commons/collections15/keyvalue/AbstractMapEntry.java0000644000175000017500000000560610464140761033400 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.keyvalue; import java.util.Map; /** * Abstract Pair class to assist with creating correct Map Entry implementations. * * @author James Strachan * @author Michael A. Smith * @author Neil O'Toole * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:32 $ * @since Commons Collections 3.0 */ public abstract class AbstractMapEntry extends AbstractKeyValue implements Map.Entry { /** * Constructs a new entry with the given key and given value. * * @param key the key for the entry, may be null * @param value the value for the entry, may be null */ protected AbstractMapEntry(K key, V value) { super(key, value); } // Map.Entry interface //------------------------------------------------------------------------- /** * Sets the value stored in this Map Entry. *

          * This Map Entry is not connected to a Map, so only the local data is changed. * * @param value the new value * @return the previous value */ public V setValue(V value) { V answer = this.value; this.value = value; return answer; } /** * Compares this Map Entry with another Map Entry. *

          * Implemented per API documentation of {@link java.util.Map.Entry#equals(Object)} * * @param obj the object to compare to * @return true if equal key and value */ public boolean equals(Object obj) { if (obj == this) { return true; } if (obj instanceof Map.Entry == false) { return false; } Map.Entry other = (Map.Entry) obj; return (getKey() == null ? other.getKey() == null : getKey().equals(other.getKey())) && (getValue() == null ? other.getValue() == null : getValue().equals(other.getValue())); } /** * Gets a hashCode compatible with the equals method. *

          * Implemented per API documentation of {@link java.util.Map.Entry#hashCode()} * * @return a suitable hash code */ public int hashCode() { return (getKey() == null ? 0 : getKey().hashCode()) ^ (getValue() == null ? 0 : getValue().hashCode()); } } collections-generic-4.01/src/java/org/apache/commons/collections15/keyvalue/package.html0000644000175000017500000000214110464140761031562 0ustar giovannigiovanni

          This package contains implementations of collection and map related key/value classes. These are usually used in maps, however they can be used as data holders in any collection.

          The following key/value designs are included:

          • Map Entry - various map entry implementations
          • KeyValue - a key and value pair, without map entry semantics
          • MultiKey - a holder of multiple keys tied together
          collections-generic-4.01/src/java/org/apache/commons/collections15/ResettableIterator.java0000644000175000017500000000230610464140760032125 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15; import java.util.Iterator; /** * Defines an iterator that can be reset back to an initial state. *

          * This interface allows an iterator to be repeatedly reused. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:19 $ * @since Commons Collections 3.0 */ public interface ResettableIterator extends Iterator { /** * Resets the iterator back to the position at which the iterator * was created. */ public void reset(); } collections-generic-4.01/src/java/org/apache/commons/collections15/Closure.java0000644000175000017500000000323610464140764027744 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15; /** * Defines a functor interface implemented by classes that do something. *

          * A Closure represents a block of code which is executed from * inside some block, function or iteration. It operates an input object. *

          * Standard implementations of common closures are provided by * {@link ClosureUtils}. These include method invokation and for/while loops. * * @author James Strachan * @author Nicola Ken Barozzi * @author Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:19 $ * @since Commons Collections 1.0 */ public interface Closure { /** * Performs an action on the specified input object. * * @param input the input to execute on * @throws ClassCastException (runtime) if the input is the wrong class * @throws IllegalArgumentException (runtime) if the input is invalid * @throws FunctorException (runtime) if any other error occurs */ public void execute(T input); } collections-generic-4.01/src/java/org/apache/commons/collections15/bidimap/0000755000175000017500000000000011664401370027062 5ustar giovannigiovanni././@LongLink0000000000000000000000000000016000000000000011562 Lustar rootrootcollections-generic-4.01/src/java/org/apache/commons/collections15/bidimap/AbstractOrderedBidiMapDecorator.javacollections-generic-4.01/src/java/org/apache/commons/collections15/bidimap/AbstractOrderedBidiMapDec0000644000175000017500000000541510464140755033730 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.bidimap; import org.apache.commons.collections15.OrderedBidiMap; import org.apache.commons.collections15.OrderedMapIterator; /** * Provides a base decorator that enables additional functionality to be added * to an OrderedBidiMap via decoration. *

          * Methods are forwarded directly to the decorated map. *

          * This implementation does not perform any special processing with the map views. * Instead it simply returns the inverse from the wrapped map. This may be * undesirable, for example if you are trying to write a validating implementation * it would provide a loophole around the validation. * But, you might want that loophole, so this class is kept simple. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:19 $ * @since Commons Collections 3.0 */ public abstract class AbstractOrderedBidiMapDecorator extends AbstractBidiMapDecorator implements OrderedBidiMap { /** * Constructor that wraps (not copies). * * @param map the map to decorate, must not be null * @throws IllegalArgumentException if the collection is null */ protected AbstractOrderedBidiMapDecorator(OrderedBidiMap map) { super(map); } /** * Gets the map being decorated. * * @return the decorated map */ protected OrderedBidiMap getOrderedBidiMap() { return (OrderedBidiMap) map; } //----------------------------------------------------------------------- public OrderedMapIterator orderedMapIterator() { return getOrderedBidiMap().orderedMapIterator(); } public K firstKey() { return getOrderedBidiMap().firstKey(); } public K lastKey() { return getOrderedBidiMap().lastKey(); } public K nextKey(K key) { return getOrderedBidiMap().nextKey(key); } public K previousKey(K key) { return getOrderedBidiMap().previousKey(key); } public OrderedBidiMap inverseOrderedBidiMap() { return getOrderedBidiMap().inverseOrderedBidiMap(); } } ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootcollections-generic-4.01/src/java/org/apache/commons/collections15/bidimap/AbstractBidiMapDecorator.javacollections-generic-4.01/src/java/org/apache/commons/collections15/bidimap/AbstractBidiMapDecorator.0000644000175000017500000000522710464140762033727 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.bidimap; import org.apache.commons.collections15.BidiMap; import org.apache.commons.collections15.MapIterator; import org.apache.commons.collections15.map.AbstractMapDecorator; import java.util.Set; /** * Provides a base decorator that enables additional functionality to be added * to a BidiMap via decoration. *

          * Methods are forwarded directly to the decorated map. *

          * This implementation does not perform any special processing with the map views. * Instead it simply returns the set/collection from the wrapped map. This may be * undesirable, for example if you are trying to write a validating implementation * it would provide a loophole around the validation. * But, you might want that loophole, so this class is kept simple. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:19 $ * @since Commons Collections 3.0 */ public abstract class AbstractBidiMapDecorator extends AbstractMapDecorator implements BidiMap { /** * Constructor that wraps (not copies). * * @param map the map to decorate, must not be null * @throws IllegalArgumentException if the collection is null */ protected AbstractBidiMapDecorator(BidiMap map) { super(map); } /** * Gets the map being decorated. * * @return the decorated map */ protected BidiMap getBidiMap() { return (BidiMap) map; } //----------------------------------------------------------------------- public MapIterator mapIterator() { return getBidiMap().mapIterator(); } public K getKey(Object value) { return getBidiMap().getKey(value); } public K removeValue(Object value) { return getBidiMap().removeValue(value); } public BidiMap inverseBidiMap() { return getBidiMap().inverseBidiMap(); } public Set values() { return getBidiMap().values(); } } ././@LongLink0000000000000000000000000000015700000000000011570 Lustar rootrootcollections-generic-4.01/src/java/org/apache/commons/collections15/bidimap/AbstractSortedBidiMapDecorator.javacollections-generic-4.01/src/java/org/apache/commons/collections15/bidimap/AbstractSortedBidiMapDeco0000644000175000017500000000534610464140755033766 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.bidimap; import org.apache.commons.collections15.SortedBidiMap; import java.util.Comparator; import java.util.SortedMap; /** * Provides a base decorator that enables additional functionality to be added * to a SortedBidiMap via decoration. *

          * Methods are forwarded directly to the decorated map. *

          * This implementation does not perform any special processing with the map views. * Instead it simply returns the inverse from the wrapped map. This may be * undesirable, for example if you are trying to write a validating implementation * it would provide a loophole around the validation. * But, you might want that loophole, so this class is kept simple. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:19 $ * @since Commons Collections 3.0 */ public abstract class AbstractSortedBidiMapDecorator extends AbstractOrderedBidiMapDecorator implements SortedBidiMap { /** * Constructor that wraps (not copies). * * @param map the map to decorate, must not be null * @throws IllegalArgumentException if the collection is null */ public AbstractSortedBidiMapDecorator(SortedBidiMap map) { super(map); } /** * Gets the map being decorated. * * @return the decorated map */ protected SortedBidiMap getSortedBidiMap() { return (SortedBidiMap) map; } //----------------------------------------------------------------------- public SortedBidiMap inverseSortedBidiMap() { return getSortedBidiMap().inverseSortedBidiMap(); } public Comparator comparator() { return getSortedBidiMap().comparator(); } public SortedMap subMap(K fromKey, K toKey) { return getSortedBidiMap().subMap(fromKey, toKey); } public SortedMap headMap(K toKey) { return getSortedBidiMap().headMap(toKey); } public SortedMap tailMap(K fromKey) { return getSortedBidiMap().tailMap(fromKey); } } collections-generic-4.01/src/java/org/apache/commons/collections15/bidimap/TreeBidiMap.java0000644000175000017500000021536510464140756032073 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.bidimap; import org.apache.commons.collections15.*; import org.apache.commons.collections15.iterators.EmptyOrderedMapIterator; import org.apache.commons.collections15.keyvalue.UnmodifiableMapEntry; import java.util.*; /** * Red-Black tree-based implementation of BidiMap where all objects added * implement the Comparable interface. *

          * This class guarantees that the map will be in both ascending key order * and ascending value order, sorted according to the natural order for * the key's and value's classes. *

          * This Map is intended for applications that need to be able to look * up a key-value pairing by either key or value, and need to do so * with equal efficiency. *

          * While that goal could be accomplished by taking a pair of TreeMaps * and redirecting requests to the appropriate TreeMap (e.g., * containsKey would be directed to the TreeMap that maps values to * keys, containsValue would be directed to the TreeMap that maps keys * to values), there are problems with that implementation. * If the data contained in the TreeMaps is large, the cost of redundant * storage becomes significant. The {@link DualTreeBidiMap} and * {@link DualHashBidiMap} implementations use this approach. *

          * This solution keeps minimizes the data storage by holding data only once. * The red-black algorithm is based on java util TreeMap, but has been modified * to simultaneously map a tree node by key and by value. This doubles the * cost of put operations (but so does using two TreeMaps), and nearly doubles * the cost of remove operations (there is a savings in that the lookup of the * node to be removed only has to be performed once). And since only one node * contains the key and value, storage is significantly less than that * required by two TreeMaps. *

          * The Map.Entry instances returned by the appropriate methods will * not allow setValue() and will throw an * UnsupportedOperationException on attempts to call that method. * * @author Marc Johnson * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:19 $ * @since Commons Collections 3.0 (previously DoubleOrderedMap v2.0) */ public class TreeBidiMap implements OrderedBidiMap { private static final int KEY = 0; private static final int VALUE = 1; private static final int MAPENTRY = 2; private static final int INVERSEMAPENTRY = 3; private static final int SUM_OF_INDICES = KEY + VALUE; private static final int FIRST_INDEX = 0; private static final int NUMBER_OF_INDICES = 2; private static final String[] dataName = new String[]{"key", "value"}; private Node[] rootNode = new Node[2]; private int nodeCount = 0; private int modifications = 0; private Set keySet; private Set valuesSet; private Set entrySet; private TreeBidiMap.Inverse inverse = null; //----------------------------------------------------------------------- /** * Constructs a new empty TreeBidiMap. */ public TreeBidiMap() { super(); } /** * Constructs a new TreeBidiMap by copying an existing Map. * * @param map the map to copy * @throws ClassCastException if the keys/values in the map are * not Comparable or are not mutually comparable * @throws NullPointerException if any key or value in the map is null */ public TreeBidiMap(final Map map) { super(); putAll(map); } //----------------------------------------------------------------------- /** * Returns the number of key-value mappings in this map. * * @return the number of key-value mappings in this map */ public int size() { return nodeCount; } /** * Checks whether the map is empty or not. * * @return true if the map is empty */ public boolean isEmpty() { return (nodeCount == 0); } /** * Checks whether this map contains the a mapping for the specified key. *

          * The key must implement Comparable. * * @param key key whose presence in this map is to be tested * @return true if this map contains a mapping for the specified key * @throws ClassCastException if the key is of an inappropriate type * @throws NullPointerException if the key is null */ public boolean containsKey(final Object key) { checkKey(key); return (lookup((Comparable) key, KEY) != null); } /** * Checks whether this map contains the a mapping for the specified value. *

          * The value must implement Comparable. * * @param value value whose presence in this map is to be tested * @return true if this map contains a mapping for the specified value * @throws ClassCastException if the value is of an inappropriate type * @throws NullPointerException if the value is null */ public boolean containsValue(final Object value) { checkValue(value); return (lookup((Comparable) value, VALUE) != null); } /** * Gets the value to which this map maps the specified key. * Returns null if the map contains no mapping for this key. *

          * The key must implement Comparable. * * @param key key whose associated value is to be returned * @return the value to which this map maps the specified key, * or null if the map contains no mapping for this key * @throws ClassCastException if the key is of an inappropriate type * @throws NullPointerException if the key is null */ public V get(final Object key) { return doGetValue(key); } /** * Puts the key-value pair into the map, replacing any previous pair. *

          * When adding a key-value pair, the value may already exist in the map * against a different key. That mapping is removed, to ensure that the * value only occurs once in the inverse map. *

               *  BidiMap map1 = new TreeBidiMap();
               *  map.put("A","B");  // contains A mapped to B, as per Map
               *  map.put("A","C");  // contains A mapped to C, as per Map
               * 

          * BidiMap map2 = new TreeBidiMap(); * map.put("A","B"); // contains A mapped to B, as per Map * map.put("C","B"); // contains C mapped to B, key A is removed *

          *

          * Both key and value must implement Comparable. * * @param key key with which the specified value is to be associated * @param value value to be associated with the specified key * @return the previous value for the key * @throws ClassCastException if the key is of an inappropriate type * @throws NullPointerException if the key is null */ public V put(final K key, final V value) { return doPutByKey(key, value); } /** * Puts all the mappings from the specified map into this map. *

          * All keys and values must implement Comparable. * * @param map the map to copy from */ public void putAll(Map map) { Iterator it = map.entrySet().iterator(); while (it.hasNext()) { Map.Entry entry = (Map.Entry) it.next(); put((K) entry.getKey(), (V) entry.getValue()); } } /** * Removes the mapping for this key from this map if present. *

          * The key must implement Comparable. * * @param key key whose mapping is to be removed from the map. * @return previous value associated with specified key, * or null if there was no mapping for key. * @throws ClassCastException if the key is of an inappropriate type * @throws NullPointerException if the key is null */ public V remove(final Object key) { return doRemoveByKey((K) key); } /** * Removes all mappings from this map. */ public void clear() { modify(); nodeCount = 0; rootNode[KEY] = null; rootNode[VALUE] = null; } //----------------------------------------------------------------------- /** * Returns the key to which this map maps the specified value. * Returns null if the map contains no mapping for this value. *

          * The value must implement Comparable. * * @param value value whose associated key is to be returned. * @return the key to which this map maps the specified value, * or null if the map contains no mapping for this value. * @throws ClassCastException if the value is of an inappropriate type * @throws NullPointerException if the value is null */ public K getKey(final Object value) { return doGetKey((Comparable) value); } /** * Removes the mapping for this value from this map if present. *

          * The value must implement Comparable. * * @param value value whose mapping is to be removed from the map * @return previous key associated with specified value, * or null if there was no mapping for value. * @throws ClassCastException if the value is of an inappropriate type * @throws NullPointerException if the value is null */ public K removeValue(final Object value) { return doRemoveByValue((Comparable) value); } //----------------------------------------------------------------------- /** * Gets the first (lowest) key currently in this map. * * @return the first (lowest) key currently in this sorted map * @throws NoSuchElementException if this map is empty */ public K firstKey() { if (nodeCount == 0) { throw new NoSuchElementException("Map is empty"); } return leastNode(rootNode[KEY], KEY).getKey(); } /** * Gets the last (highest) key currently in this map. * * @return the last (highest) key currently in this sorted map * @throws NoSuchElementException if this map is empty */ public K lastKey() { if (nodeCount == 0) { throw new NoSuchElementException("Map is empty"); } return greatestNode(rootNode[KEY], KEY).getKey(); } /** * Gets the next key after the one specified. *

          * The key must implement Comparable. * * @param key the key to search for next from * @return the next key, null if no match or at end */ public K nextKey(K key) { checkKey(key); Node node = nextGreater(lookup(key, KEY), KEY); return (node == null ? null : node.getKey()); } /** * Gets the previous key before the one specified. *

          * The key must implement Comparable. * * @param key the key to search for previous from * @return the previous key, null if no match or at start */ public K previousKey(K key) { checkKey(key); Node node = nextSmaller(lookup((Comparable) key, KEY), KEY); return (node == null ? null : node.getKey()); } //----------------------------------------------------------------------- /** * Returns a set view of the keys contained in this map in key order. *

          * The set is backed by the map, so changes to the map are reflected in * the set, and vice-versa. If the map is modified while an iteration over * the set is in progress, the results of the iteration are undefined. *

          * The set supports element removal, which removes the corresponding mapping * from the map. It does not support the add or addAll operations. * * @return a set view of the keys contained in this map. */ public Set keySet() { if (keySet == null) { keySet = new View(this, KEY, KEY); } return keySet; } //----------------------------------------------------------------------- /** * Returns a set view of the values contained in this map in key order. * The returned object can be cast to a Set. *

          * The set is backed by the map, so changes to the map are reflected in * the set, and vice-versa. If the map is modified while an iteration over * the set is in progress, the results of the iteration are undefined. *

          * The set supports element removal, which removes the corresponding mapping * from the map. It does not support the add or addAll operations. * * @return a set view of the values contained in this map. */ public Set values() { if (valuesSet == null) { valuesSet = new View(this, KEY, VALUE); } return valuesSet; } //----------------------------------------------------------------------- /** * Returns a set view of the entries contained in this map in key order. * For simple iteration through the map, the MapIterator is quicker. *

          * The set is backed by the map, so changes to the map are reflected in * the set, and vice-versa. If the map is modified while an iteration over * the set is in progress, the results of the iteration are undefined. *

          * The set supports element removal, which removes the corresponding mapping * from the map. It does not support the add or addAll operations. * The returned MapEntry objects do not support setValue. * * @return a set view of the values contained in this map. */ public Set> entrySet() { if (entrySet == null) { return new EntryView(this, KEY, MAPENTRY); } return entrySet; } //----------------------------------------------------------------------- /** * Gets an iterator over the map entries. *

          * For this map, this iterator is the fastest way to iterate over the entries. * * @return an iterator */ public MapIterator mapIterator() { if (isEmpty()) { return EmptyOrderedMapIterator.INSTANCE; } return new ViewMapIterator(this, KEY); } /** * Gets an ordered iterator over the map entries. *

          * This iterator allows both forward and reverse iteration over the entries. * * @return an iterator */ public OrderedMapIterator orderedMapIterator() { if (isEmpty()) { return EmptyOrderedMapIterator.INSTANCE; } return new ViewMapIterator(this, KEY); } //----------------------------------------------------------------------- /** * Gets the inverse map for comparison. * * @return the inverse map */ public BidiMap inverseBidiMap() { return inverseOrderedBidiMap(); } /** * Gets the inverse map for comparison. * * @return the inverse map */ public OrderedBidiMap inverseOrderedBidiMap() { if (inverse == null) { inverse = new Inverse(this); } return inverse; } //----------------------------------------------------------------------- /** * Compares for equals as per the API. * * @param obj the object to compare to * @return true if equal */ public boolean equals(Object obj) { return this.doEquals(obj, KEY); } /** * Gets the hash code value for this map as per the API. * * @return the hash code value for this map */ public int hashCode() { return this.doHashCode(KEY); } /** * Returns a string version of this Map in standard format. * * @return a standard format string version of the map */ public String toString() { return this.doToString(KEY); } //----------------------------------------------------------------------- /** * Common get logic, used to get by value * * @param value the key or value that we're looking for * @return the key (if the value was mapped) or the value (if the * key was mapped); null if we couldn't find the specified * object */ private K doGetKey(final Comparable value) { checkNonNullComparable(value); Node node = lookup(value, VALUE); if (node == null) { return null; } else { return node.getKey(); } } /** * Common get logic, used to get by key * * @param key the key or value that we're looking for * @return the key (if the value was mapped) or the value (if the * key was mapped); null if we couldn't find the specified * object */ private V doGetValue(final Object key) { checkNonNullComparable(key); Node node = lookup((Comparable) key, KEY); if (node == null) { return null; } else { return node.getValue(); } } /** * Common put logic * * @param key the key, always the main map key * @param value the value, always the main map value * @return the previously mapped value */ private V doPutByKey(final K key, final V value) { checkKeyAndValue(key, value); // store previous and remove previous mappings V prev = doGetValue(key); doPut(key, value); return prev; } /** * Common put logic * * @param key the key, always the main map key * @param value the value, always the main map value * @return the previously mapped value */ private K doPutByValue(final K key, final V value) { checkKeyAndValue(key, value); // store previous and remove previous mappings K prev = doGetKey(value); doPut(key, value); return prev; } private void doPut(final K key, final V value) { doRemoveByKey(key); doRemoveByValue(value); Node node = rootNode[KEY]; if (node == null) { // map is empty Node root = new Node(key, value); rootNode[KEY] = root; rootNode[VALUE] = root; grow(); } else { // add new mapping while (true) { int cmp = compare(key, node.getKey()); if (cmp == 0) { // shouldn't happen throw new IllegalArgumentException("Cannot store a duplicate key (\"" + key + "\") in this Map"); } else if (cmp < 0) { if (node.getLeft(KEY) != null) { node = node.getLeft(KEY); } else { Node newNode = new Node(key, value); insertValue(newNode); node.setLeft(newNode, KEY); newNode.setParent(node, KEY); doRedBlackInsert(newNode, KEY); grow(); break; } } else { // cmp > 0 if (node.getRight(KEY) != null) { node = node.getRight(KEY); } else { Node newNode = new Node(key, value); insertValue(newNode); node.setRight(newNode, KEY); newNode.setParent(node, KEY); doRedBlackInsert(newNode, KEY); grow(); break; } } } } } /** * Remove by key * * @param key the key * @return the key, if remove by value, or the value, if remove by * key. null if the specified key or value could not be * found */ private V doRemoveByKey(final K key) { Node node = lookup(key, KEY); V rval = null; if (node != null) { rval = node.getValue(); doRedBlackDelete(node); } return rval; } /** * Remove by value * * @param value the value * @return the key, if remove by value, or the value, if remove by * key. null if the specified key or value could not be * found */ private K doRemoveByValue(final Comparable value) { Node node = lookup(value, VALUE); K rval = null; if (node != null) { rval = node.getKey(); doRedBlackDelete(node); } return rval; } /** * do the actual lookup of a piece of data * * @param data the key or value to be looked up * @param index the KEY or VALUE int * @return the desired Node, or null if there is no mapping of the * specified data */ private Node lookup(final Comparable data, final int index) { Node rval = null; Node node = rootNode[index]; while (node != null) { int cmp = compare(data, node.getData(index)); if (cmp == 0) { rval = node; break; } else { node = (cmp < 0) ? node.getLeft(index) : node.getRight(index); } } return rval; } /** * get the next larger node from the specified node * * @param node the node to be searched from * @param index the KEY or VALUE int * @return the specified node */ private Node nextGreater(final Node node, final int index) { Node rval = null; if (node == null) { rval = null; } else if (node.getRight(index) != null) { // everything to the node's right is larger. The least of // the right node's descendants is the next larger node rval = leastNode(node.getRight(index), index); } else { // traverse up our ancestry until we find an ancestor that // is null or one whose left child is our ancestor. If we // find a null, then this node IS the largest node in the // tree, and there is no greater node. Otherwise, we are // the largest node in the subtree on that ancestor's left // ... and that ancestor is the next greatest node Node parent = node.getParent(index); Node child = node; while ((parent != null) && (child == parent.getRight(index))) { child = parent; parent = parent.getParent(index); } rval = parent; } return rval; } /** * get the next larger node from the specified node * * @param node the node to be searched from * @param index the KEY or VALUE int * @return the specified node */ private Node nextSmaller(final Node node, final int index) { Node rval = null; if (node == null) { rval = null; } else if (node.getLeft(index) != null) { // everything to the node's left is smaller. The greatest of // the left node's descendants is the next smaller node rval = greatestNode(node.getLeft(index), index); } else { // traverse up our ancestry until we find an ancestor that // is null or one whose right child is our ancestor. If we // find a null, then this node IS the largest node in the // tree, and there is no greater node. Otherwise, we are // the largest node in the subtree on that ancestor's right // ... and that ancestor is the next greatest node Node parent = node.getParent(index); Node child = node; while ((parent != null) && (child == parent.getLeft(index))) { child = parent; parent = parent.getParent(index); } rval = parent; } return rval; } //----------------------------------------------------------------------- /** * Get the opposite index of the specified index * * @param index the KEY or VALUE int * @return VALUE (if KEY was specified), else KEY */ private static int oppositeIndex(final int index) { // old trick ... to find the opposite of a value, m or n, // subtract the value from the sum of the two possible // values. (m + n) - m = n; (m + n) - n = m return SUM_OF_INDICES - index; } /** * Compare two objects * * @param o1 the first object * @param o2 the second object * @return negative value if o1 < o2; 0 if o1 == o2; positive * value if o1 > o2 */ private static int compare(final Comparable o1, final Comparable o2) { return o1.compareTo(o2); } /** * Find the least node from a given node. * * @param node the node from which we will start searching * @param index the KEY or VALUE int * @return the smallest node, from the specified node, in the * specified mapping */ private static Node leastNode(final Node node, final int index) { Node rval = node; if (rval != null) { while (rval.getLeft(index) != null) { rval = rval.getLeft(index); } } return rval; } /** * Find the greatest node from a given node. * * @param node the node from which we will start searching * @param index the KEY or VALUE int * @return the greatest node, from the specified node */ private static Node greatestNode(final Node node, final int index) { Node rval = node; if (rval != null) { while (rval.getRight(index) != null) { rval = rval.getRight(index); } } return rval; } /** * copy the color from one node to another, dealing with the fact * that one or both nodes may, in fact, be null * * @param from the node whose color we're copying; may be null * @param to the node whose color we're changing; may be null * @param index the KEY or VALUE int */ private static void copyColor(final Node from, final Node to, final int index) { if (to != null) { if (from == null) { // by default, make it black to.setBlack(index); } else { to.copyColor(from, index); } } } /** * is the specified node red? if the node does not exist, no, it's * black, thank you * * @param node the node (may be null) in question * @param index the KEY or VALUE int */ private static boolean isRed(final Node node, final int index) { return ((node == null) ? false : node.isRed(index)); } /** * is the specified black red? if the node does not exist, sure, * it's black, thank you * * @param node the node (may be null) in question * @param index the KEY or VALUE int */ private static boolean isBlack(final Node node, final int index) { return ((node == null) ? true : node.isBlack(index)); } /** * force a node (if it exists) red * * @param node the node (may be null) in question * @param index the KEY or VALUE int */ private static void makeRed(final Node node, final int index) { if (node != null) { node.setRed(index); } } /** * force a node (if it exists) black * * @param node the node (may be null) in question * @param index the KEY or VALUE int */ private static void makeBlack(final Node node, final int index) { if (node != null) { node.setBlack(index); } } /** * get a node's grandparent. mind you, the node, its parent, or * its grandparent may not exist. no problem * * @param node the node (may be null) in question * @param index the KEY or VALUE int */ private static Node getGrandParent(final Node node, final int index) { return getParent(getParent(node, index), index); } /** * get a node's parent. mind you, the node, or its parent, may not * exist. no problem * * @param node the node (may be null) in question * @param index the KEY or VALUE int */ private static Node getParent(final Node node, final int index) { return ((node == null) ? null : node.getParent(index)); } /** * get a node's right child. mind you, the node may not exist. no * problem * * @param node the node (may be null) in question * @param index the KEY or VALUE int */ private static Node getRightChild(final Node node, final int index) { return (node == null) ? null : node.getRight(index); } /** * get a node's left child. mind you, the node may not exist. no * problem * * @param node the node (may be null) in question * @param index the KEY or VALUE int */ private static Node getLeftChild(final Node node, final int index) { return (node == null) ? null : node.getLeft(index); } /** * is this node its parent's left child? mind you, the node, or * its parent, may not exist. no problem. if the node doesn't * exist ... it's its non-existent parent's left child. If the * node does exist but has no parent ... no, we're not the * non-existent parent's left child. Otherwise (both the specified * node AND its parent exist), check. * * @param node the node (may be null) in question * @param index the KEY or VALUE int */ private static boolean isLeftChild(final Node node, final int index) { return (node == null) ? true : ((node.getParent(index) == null) ? false : (node == node.getParent(index).getLeft(index))); } /** * is this node its parent's right child? mind you, the node, or * its parent, may not exist. no problem. if the node doesn't * exist ... it's its non-existent parent's right child. If the * node does exist but has no parent ... no, we're not the * non-existent parent's right child. Otherwise (both the * specified node AND its parent exist), check. * * @param node the node (may be null) in question * @param index the KEY or VALUE int */ private static boolean isRightChild(final Node node, final int index) { return (node == null) ? true : ((node.getParent(index) == null) ? false : (node == node.getParent(index).getRight(index))); } /** * do a rotate left. standard fare in the world of balanced trees * * @param node the node to be rotated * @param index the KEY or VALUE int */ private void rotateLeft(final Node node, final int index) { Node rightChild = node.getRight(index); node.setRight(rightChild.getLeft(index), index); if (rightChild.getLeft(index) != null) { rightChild.getLeft(index).setParent(node, index); } rightChild.setParent(node.getParent(index), index); if (node.getParent(index) == null) { // node was the root ... now its right child is the root rootNode[index] = rightChild; } else if (node.getParent(index).getLeft(index) == node) { node.getParent(index).setLeft(rightChild, index); } else { node.getParent(index).setRight(rightChild, index); } rightChild.setLeft(node, index); node.setParent(rightChild, index); } /** * do a rotate right. standard fare in the world of balanced trees * * @param node the node to be rotated * @param index the KEY or VALUE int */ private void rotateRight(final Node node, final int index) { Node leftChild = node.getLeft(index); node.setLeft(leftChild.getRight(index), index); if (leftChild.getRight(index) != null) { leftChild.getRight(index).setParent(node, index); } leftChild.setParent(node.getParent(index), index); if (node.getParent(index) == null) { // node was the root ... now its left child is the root rootNode[index] = leftChild; } else if (node.getParent(index).getRight(index) == node) { node.getParent(index).setRight(leftChild, index); } else { node.getParent(index).setLeft(leftChild, index); } leftChild.setRight(node, index); node.setParent(leftChild, index); } /** * complicated red-black insert stuff. Based on Sun's TreeMap * implementation, though it's barely recognizable any more * * @param insertedNode the node to be inserted * @param index the KEY or VALUE int */ private void doRedBlackInsert(final Node insertedNode, final int index) { Node currentNode = insertedNode; makeRed(currentNode, index); while ((currentNode != null) && (currentNode != rootNode[index]) && (isRed(currentNode.getParent(index), index))) { if (isLeftChild(getParent(currentNode, index), index)) { Node y = getRightChild(getGrandParent(currentNode, index), index); if (isRed(y, index)) { makeBlack(getParent(currentNode, index), index); makeBlack(y, index); makeRed(getGrandParent(currentNode, index), index); currentNode = getGrandParent(currentNode, index); } else { if (isRightChild(currentNode, index)) { currentNode = getParent(currentNode, index); rotateLeft(currentNode, index); } makeBlack(getParent(currentNode, index), index); makeRed(getGrandParent(currentNode, index), index); if (getGrandParent(currentNode, index) != null) { rotateRight(getGrandParent(currentNode, index), index); } } } else { // just like clause above, except swap left for right Node y = getLeftChild(getGrandParent(currentNode, index), index); if (isRed(y, index)) { makeBlack(getParent(currentNode, index), index); makeBlack(y, index); makeRed(getGrandParent(currentNode, index), index); currentNode = getGrandParent(currentNode, index); } else { if (isLeftChild(currentNode, index)) { currentNode = getParent(currentNode, index); rotateRight(currentNode, index); } makeBlack(getParent(currentNode, index), index); makeRed(getGrandParent(currentNode, index), index); if (getGrandParent(currentNode, index) != null) { rotateLeft(getGrandParent(currentNode, index), index); } } } } makeBlack(rootNode[index], index); } /** * complicated red-black delete stuff. Based on Sun's TreeMap * implementation, though it's barely recognizable any more * * @param deletedNode the node to be deleted */ private void doRedBlackDelete(final Node deletedNode) { for (int index = FIRST_INDEX; index < NUMBER_OF_INDICES; index++) { // if deleted node has both left and children, swap with // the next greater node if ((deletedNode.getLeft(index) != null) && (deletedNode.getRight(index) != null)) { swapPosition(nextGreater(deletedNode, index), deletedNode, index); } Node replacement = ((deletedNode.getLeft(index) != null) ? deletedNode.getLeft(index) : deletedNode.getRight(index)); if (replacement != null) { replacement.setParent(deletedNode.getParent(index), index); if (deletedNode.getParent(index) == null) { rootNode[index] = replacement; } else if (deletedNode == deletedNode.getParent(index).getLeft(index)) { deletedNode.getParent(index).setLeft(replacement, index); } else { deletedNode.getParent(index).setRight(replacement, index); } deletedNode.setLeft(null, index); deletedNode.setRight(null, index); deletedNode.setParent(null, index); if (isBlack(deletedNode, index)) { doRedBlackDeleteFixup(replacement, index); } } else { // replacement is null if (deletedNode.getParent(index) == null) { // empty tree rootNode[index] = null; } else { // deleted node had no children if (isBlack(deletedNode, index)) { doRedBlackDeleteFixup(deletedNode, index); } if (deletedNode.getParent(index) != null) { if (deletedNode == deletedNode.getParent(index).getLeft(index)) { deletedNode.getParent(index).setLeft(null, index); } else { deletedNode.getParent(index).setRight(null, index); } deletedNode.setParent(null, index); } } } } shrink(); } /** * complicated red-black delete stuff. Based on Sun's TreeMap * implementation, though it's barely recognizable any more. This * rebalances the tree (somewhat, as red-black trees are not * perfectly balanced -- perfect balancing takes longer) * * @param replacementNode the node being replaced * @param index the KEY or VALUE int */ private void doRedBlackDeleteFixup(final Node replacementNode, final int index) { Node currentNode = replacementNode; while ((currentNode != rootNode[index]) && (isBlack(currentNode, index))) { if (isLeftChild(currentNode, index)) { Node siblingNode = getRightChild(getParent(currentNode, index), index); if (isRed(siblingNode, index)) { makeBlack(siblingNode, index); makeRed(getParent(currentNode, index), index); rotateLeft(getParent(currentNode, index), index); siblingNode = getRightChild(getParent(currentNode, index), index); } if (isBlack(getLeftChild(siblingNode, index), index) && isBlack(getRightChild(siblingNode, index), index)) { makeRed(siblingNode, index); currentNode = getParent(currentNode, index); } else { if (isBlack(getRightChild(siblingNode, index), index)) { makeBlack(getLeftChild(siblingNode, index), index); makeRed(siblingNode, index); rotateRight(siblingNode, index); siblingNode = getRightChild(getParent(currentNode, index), index); } copyColor(getParent(currentNode, index), siblingNode, index); makeBlack(getParent(currentNode, index), index); makeBlack(getRightChild(siblingNode, index), index); rotateLeft(getParent(currentNode, index), index); currentNode = rootNode[index]; } } else { Node siblingNode = getLeftChild(getParent(currentNode, index), index); if (isRed(siblingNode, index)) { makeBlack(siblingNode, index); makeRed(getParent(currentNode, index), index); rotateRight(getParent(currentNode, index), index); siblingNode = getLeftChild(getParent(currentNode, index), index); } if (isBlack(getRightChild(siblingNode, index), index) && isBlack(getLeftChild(siblingNode, index), index)) { makeRed(siblingNode, index); currentNode = getParent(currentNode, index); } else { if (isBlack(getLeftChild(siblingNode, index), index)) { makeBlack(getRightChild(siblingNode, index), index); makeRed(siblingNode, index); rotateLeft(siblingNode, index); siblingNode = getLeftChild(getParent(currentNode, index), index); } copyColor(getParent(currentNode, index), siblingNode, index); makeBlack(getParent(currentNode, index), index); makeBlack(getLeftChild(siblingNode, index), index); rotateRight(getParent(currentNode, index), index); currentNode = rootNode[index]; } } } makeBlack(currentNode, index); } /** * swap two nodes (except for their content), taking care of * special cases where one is the other's parent ... hey, it * happens. * * @param x one node * @param y another node * @param index the KEY or VALUE int */ private void swapPosition(final Node x, final Node y, final int index) { // Save initial values. Node xFormerParent = x.getParent(index); Node xFormerLeftChild = x.getLeft(index); Node xFormerRightChild = x.getRight(index); Node yFormerParent = y.getParent(index); Node yFormerLeftChild = y.getLeft(index); Node yFormerRightChild = y.getRight(index); boolean xWasLeftChild = (x.getParent(index) != null) && (x == x.getParent(index).getLeft(index)); boolean yWasLeftChild = (y.getParent(index) != null) && (y == y.getParent(index).getLeft(index)); // Swap, handling special cases of one being the other's parent. if (x == yFormerParent) { // x was y's parent x.setParent(y, index); if (yWasLeftChild) { y.setLeft(x, index); y.setRight(xFormerRightChild, index); } else { y.setRight(x, index); y.setLeft(xFormerLeftChild, index); } } else { x.setParent(yFormerParent, index); if (yFormerParent != null) { if (yWasLeftChild) { yFormerParent.setLeft(x, index); } else { yFormerParent.setRight(x, index); } } y.setLeft(xFormerLeftChild, index); y.setRight(xFormerRightChild, index); } if (y == xFormerParent) { // y was x's parent y.setParent(x, index); if (xWasLeftChild) { x.setLeft(y, index); x.setRight(yFormerRightChild, index); } else { x.setRight(y, index); x.setLeft(yFormerLeftChild, index); } } else { y.setParent(xFormerParent, index); if (xFormerParent != null) { if (xWasLeftChild) { xFormerParent.setLeft(y, index); } else { xFormerParent.setRight(y, index); } } x.setLeft(yFormerLeftChild, index); x.setRight(yFormerRightChild, index); } // Fix children's parent pointers if (x.getLeft(index) != null) { x.getLeft(index).setParent(x, index); } if (x.getRight(index) != null) { x.getRight(index).setParent(x, index); } if (y.getLeft(index) != null) { y.getLeft(index).setParent(y, index); } if (y.getRight(index) != null) { y.getRight(index).setParent(y, index); } x.swapColors(y, index); // Check if root changed if (rootNode[index] == x) { rootNode[index] = y; } else if (rootNode[index] == y) { rootNode[index] = x; } } /** * check if an object is fit to be proper input ... has to be * Comparable and non-null * * @param o the object being checked * @throws NullPointerException if o is null * @throws ClassCastException if o is not Comparable */ private static void checkNonNullComparable(final Object o) { if (o == null) { throw new NullPointerException("Cannot be null"); } if (!(o instanceof Comparable)) { throw new ClassCastException("Must be Comparable"); } } /** * check a key for validity (non-null and implements Comparable) * * @param key the key to be checked * @throws NullPointerException if key is null * @throws ClassCastException if key is not Comparable */ private static void checkKey(final Object key) { checkNonNullComparable(key); } /** * check a value for validity (non-null and implements Comparable) * * @param value the value to be checked * @throws NullPointerException if value is null * @throws ClassCastException if value is not Comparable */ private static void checkValue(final Object value) { checkNonNullComparable(value); } /** * check a key and a value for validity (non-null and implements * Comparable) * * @param key the key to be checked * @param value the value to be checked * @throws NullPointerException if key or value is null * @throws ClassCastException if key or value is not Comparable */ private static void checkKeyAndValue(final Object key, final Object value) { checkKey(key); checkValue(value); } /** * increment the modification count -- used to check for * concurrent modification of the map through the map and through * an Iterator from one of its Set or Collection views */ private void modify() { modifications++; } /** * bump up the size and note that the map has changed */ private void grow() { modify(); nodeCount++; } /** * decrement the size and note that the map has changed */ private void shrink() { modify(); nodeCount--; } /** * insert a node by its value * * @param newNode the node to be inserted * @throws IllegalArgumentException if the node already exists * in the value mapping */ private void insertValue(final Node newNode) throws IllegalArgumentException { Node node = rootNode[VALUE]; while (true) { int cmp = compare(newNode.getData(VALUE), node.getData(VALUE)); if (cmp == 0) { throw new IllegalArgumentException("Cannot store a duplicate value (\"" + newNode.getData(VALUE) + "\") in this Map"); } else if (cmp < 0) { if (node.getLeft(VALUE) != null) { node = node.getLeft(VALUE); } else { node.setLeft(newNode, VALUE); newNode.setParent(node, VALUE); doRedBlackInsert(newNode, VALUE); break; } } else { // cmp > 0 if (node.getRight(VALUE) != null) { node = node.getRight(VALUE); } else { node.setRight(newNode, VALUE); newNode.setParent(node, VALUE); doRedBlackInsert(newNode, VALUE); break; } } } } //----------------------------------------------------------------------- /** * Compares for equals as per the API. * * @param obj the object to compare to * @return true if equal */ private boolean doEquals(Object obj, final int type) { if (obj == this) { return true; } if (obj instanceof Map == false) { return false; } Map other = (Map) obj; if (other.size() != size()) { return false; } if (nodeCount > 0) { try { for (MapIterator it = new ViewMapIterator(this, type); it.hasNext();) { Object key = it.next(); Object value = it.getValue(); if (value.equals(other.get(key)) == false) { return false; } } } catch (ClassCastException ex) { return false; } catch (NullPointerException ex) { return false; } } return true; } /** * Gets the hash code value for this map as per the API. * * @return the hash code value for this map */ private int doHashCode(final int type) { int total = 0; if (nodeCount > 0) { for (MapIterator it = new ViewMapIterator(this, type); it.hasNext();) { Object key = it.next(); Object value = it.getValue(); total += (key.hashCode() ^ value.hashCode()); } } return total; } /** * Gets the string form of this map as per AbstractMap. * * @return the string form of this map */ private String doToString(final int type) { if (nodeCount == 0) { return "{}"; } StringBuffer buf = new StringBuffer(nodeCount * 32); buf.append('{'); MapIterator it = new ViewMapIterator(this, type); boolean hasNext = it.hasNext(); while (hasNext) { Object key = it.next(); Object value = it.getValue(); buf.append(key == this ? "(this Map)" : key).append('=').append(value == this ? "(this Map)" : value); hasNext = it.hasNext(); if (hasNext) { buf.append(", "); } } buf.append('}'); return buf.toString(); } //----------------------------------------------------------------------- /** * A view of this map. */ static class View extends AbstractSet { /** * The parent map. */ protected final TreeBidiMap main; /** * Whether to return KEY or VALUE order. */ protected final int orderType; /** * Whether to return KEY, VALUE, MAPENTRY or INVERSEMAPENTRY data. */ protected final int dataType; /** * Constructor. * * @param main the main map * @param orderType the KEY or VALUE int for the order * @param dataType the KEY, VALUE, MAPENTRY or INVERSEMAPENTRY int */ View(final TreeBidiMap main, final int orderType, final int dataType) { super(); this.main = main; this.orderType = orderType; this.dataType = dataType; } public Iterator iterator() { return new ViewIterator(main, orderType, dataType); } public int size() { return main.size(); } public boolean contains(final Object obj) { checkNonNullComparable(obj); return (main.lookup((Comparable) obj, dataType) != null); } public boolean remove(final Object obj) { if (dataType == KEY) { return main.doRemoveByKey((K) obj) != null; } else { return main.doRemoveByValue((V) obj) != null; } } public void clear() { main.clear(); } } //----------------------------------------------------------------------- /** * An iterator over the map. */ static class ViewIterator implements OrderedIterator { /** * The parent map. */ protected final TreeBidiMap main; /** * Whether to return KEY or VALUE order. */ protected final int orderType; /** * Whether to return KEY, VALUE, MAPENTRY or INVERSEMAPENTRY data. */ protected final int dataType; /** * The last node returned by the iterator. */ protected Node lastReturnedNode; /** * The next node to be returned by the iterator. */ protected Node nextNode; /** * The previous node in the sequence returned by the iterator. */ protected Node previousNode; /** * The modification count. */ private int expectedModifications; /** * Constructor. * * @param main the main map * @param orderType the KEY or VALUE int for the order * @param dataType the KEY, VALUE, MAPENTRY or INVERSEMAPENTRY int */ ViewIterator(final TreeBidiMap main, final int orderType, final int dataType) { super(); this.main = main; this.orderType = orderType; this.dataType = dataType; expectedModifications = main.modifications; nextNode = leastNode(main.rootNode[orderType], orderType); lastReturnedNode = null; previousNode = null; } public final boolean hasNext() { return (nextNode != null); } public final Object next() { if (nextNode == null) { throw new NoSuchElementException(); } if (main.modifications != expectedModifications) { throw new ConcurrentModificationException(); } lastReturnedNode = nextNode; previousNode = nextNode; nextNode = main.nextGreater(nextNode, orderType); return doGetData(); } public boolean hasPrevious() { return (previousNode != null); } public Object previous() { if (previousNode == null) { throw new NoSuchElementException(); } if (main.modifications != expectedModifications) { throw new ConcurrentModificationException(); } nextNode = lastReturnedNode; if (nextNode == null) { nextNode = main.nextGreater(previousNode, orderType); } lastReturnedNode = previousNode; previousNode = main.nextSmaller(previousNode, orderType); return doGetData(); } /** * Gets the data value for the lastReturnedNode field. * * @return the data value */ protected Object doGetData() { switch (dataType) { case KEY: return lastReturnedNode.getKey(); case VALUE: return lastReturnedNode.getValue(); case MAPENTRY: return lastReturnedNode; case INVERSEMAPENTRY: return new UnmodifiableMapEntry(lastReturnedNode.getValue(), lastReturnedNode.getKey()); } return null; } public final void remove() { if (lastReturnedNode == null) { throw new IllegalStateException(); } if (main.modifications != expectedModifications) { throw new ConcurrentModificationException(); } main.doRedBlackDelete(lastReturnedNode); expectedModifications++; lastReturnedNode = null; if (nextNode == null) { previousNode = main.greatestNode(main.rootNode[orderType], orderType); } else { previousNode = main.nextSmaller(nextNode, orderType); } } } //----------------------------------------------------------------------- /** * An iterator over the map. */ static class ViewMapIterator extends ViewIterator implements OrderedMapIterator { private final int oppositeType; /** * Constructor. * * @param main the main map * @param orderType the KEY or VALUE int for the order */ ViewMapIterator(final TreeBidiMap main, final int orderType) { super(main, orderType, orderType); this.oppositeType = oppositeIndex(dataType); } public Object getKey() { if (lastReturnedNode == null) { throw new IllegalStateException("Iterator getKey() can only be called after next() and before remove()"); } return lastReturnedNode.getData(dataType); } public Object getValue() { if (lastReturnedNode == null) { throw new IllegalStateException("Iterator getValue() can only be called after next() and before remove()"); } return lastReturnedNode.getData(oppositeType); } public Object setValue(final Object obj) { throw new UnsupportedOperationException(); } } //----------------------------------------------------------------------- /** * A view of this map. */ static class EntryView extends View { private final int oppositeType; /** * Constructor. * * @param main the main map * @param orderType the KEY or VALUE int for the order * @param dataType the MAPENTRY or INVERSEMAPENTRY int for the returned data */ EntryView(final TreeBidiMap main, final int orderType, final int dataType) { super(main, orderType, dataType); this.oppositeType = main.oppositeIndex(orderType); } public boolean contains(Object obj) { if (obj instanceof Map.Entry == false) { return false; } Map.Entry entry = (Map.Entry) obj; Object value = entry.getValue(); Node node = main.lookup((Comparable) entry.getKey(), orderType); return (node != null && node.getData(oppositeType).equals(value)); } public boolean remove(Object obj) { if (obj instanceof Map.Entry == false) { return false; } Map.Entry entry = (Map.Entry) obj; Object value = entry.getValue(); Node node = main.lookup((Comparable) entry.getKey(), orderType); if (node != null && node.getData(oppositeType).equals(value)) { main.doRedBlackDelete(node); return true; } return false; } } //----------------------------------------------------------------------- /** * A node used to store the data. */ static class Node implements Map.Entry, KeyValue { private K key; private V value; private Node[] leftNode; private Node[] rightNode; private Node[] parentNode; private boolean[] blackColor; private int hashcodeValue; private boolean calculatedHashCode; /** * Make a new cell with given key and value, and with null * links, and black (true) colors. * * @param key * @param value */ Node(final K key, final V value) { super(); this.key = key; this.value = value; leftNode = new Node[2]; rightNode = new Node[2]; parentNode = new Node[2]; blackColor = new boolean[]{true, true}; calculatedHashCode = false; } /** * Get the specified data. * * @param index the KEY or VALUE int * @return the key or value */ private Comparable getData(final int index) { if (index == KEY) { return key; } else { return value; } } /** * Set this node's left node. * * @param node the new left node * @param index the KEY or VALUE int */ private void setLeft(final Node node, final int index) { leftNode[index] = node; } /** * Get the left node. * * @param index the KEY or VALUE int * @return the left node, may be null */ private Node getLeft(final int index) { return leftNode[index]; } /** * Set this node's right node. * * @param node the new right node * @param index the KEY or VALUE int */ private void setRight(final Node node, final int index) { rightNode[index] = node; } /** * Get the right node. * * @param index the KEY or VALUE int * @return the right node, may be null */ private Node getRight(final int index) { return rightNode[index]; } /** * Set this node's parent node. * * @param node the new parent node * @param index the KEY or VALUE int */ private void setParent(final Node node, final int index) { parentNode[index] = node; } /** * Get the parent node. * * @param index the KEY or VALUE int * @return the parent node, may be null */ private Node getParent(final int index) { return parentNode[index]; } /** * Exchange colors with another node. * * @param node the node to swap with * @param index the KEY or VALUE int */ private void swapColors(final Node node, final int index) { // Swap colors -- old hacker's trick blackColor[index] ^= node.blackColor[index]; node.blackColor[index] ^= blackColor[index]; blackColor[index] ^= node.blackColor[index]; } /** * Is this node black? * * @param index the KEY or VALUE int * @return true if black (which is represented as a true boolean) */ private boolean isBlack(final int index) { return blackColor[index]; } /** * Is this node red? * * @param index the KEY or VALUE int * @return true if non-black */ private boolean isRed(final int index) { return !blackColor[index]; } /** * Make this node black. * * @param index the KEY or VALUE int */ private void setBlack(final int index) { blackColor[index] = true; } /** * Make this node red. * * @param index the KEY or VALUE int */ private void setRed(final int index) { blackColor[index] = false; } /** * Make this node the same color as another * * @param node the node whose color we're adopting * @param index the KEY or VALUE int */ private void copyColor(final Node node, final int index) { blackColor[index] = node.blackColor[index]; } //------------------------------------------------------------------- /** * Gets the key. * * @return the key corresponding to this entry. */ public K getKey() { return key; } /** * Gets the value. * * @return the value corresponding to this entry. */ public V getValue() { return value; } /** * Optional operation that is not permitted in this implementation * * @param ignored * @return does not return * @throws UnsupportedOperationException always */ public V setValue(final V ignored) throws UnsupportedOperationException { throw new UnsupportedOperationException("Map.Entry.setValue is not supported"); } /** * Compares the specified object with this entry for equality. * Returns true if the given object is also a map entry and * the two entries represent the same mapping. * * @param obj the object to be compared for equality with this entry. * @return true if the specified object is equal to this entry. */ public boolean equals(final Object obj) { if (obj == this) { return true; } if (!(obj instanceof Map.Entry)) { return false; } Map.Entry e = (Map.Entry) obj; return key.equals(e.getKey()) && value.equals(e.getValue()); } /** * @return the hash code value for this map entry. */ public int hashCode() { if (!calculatedHashCode) { hashcodeValue = key.hashCode() ^ value.hashCode(); calculatedHashCode = true; } return hashcodeValue; } } //----------------------------------------------------------------------- /** * A node used to store the data. */ static class Inverse implements OrderedBidiMap { /** * The parent map. */ private final TreeBidiMap main; /** * Store the keySet once created. */ private Set keySet; /** * Store the valuesSet once created. */ private Set valuesSet; /** * Store the entrySet once created. */ private Set entrySet; /** * Constructor. * * @param main the main map */ Inverse(final TreeBidiMap main) { super(); this.main = main; } public int size() { return main.size(); } public boolean isEmpty() { return main.isEmpty(); } public K get(final Object key) { return main.getKey((V) key); } public V getKey(final Object value) { return main.get(value); } public boolean containsKey(final Object key) { return main.containsValue(key); } public boolean containsValue(final Object value) { return main.containsKey(value); } public V firstKey() { if (main.nodeCount == 0) { throw new NoSuchElementException("Map is empty"); } return main.leastNode(main.rootNode[VALUE], VALUE).getValue(); } public V lastKey() { if (main.nodeCount == 0) { throw new NoSuchElementException("Map is empty"); } return main.greatestNode(main.rootNode[VALUE], VALUE).getValue(); } public V nextKey(V key) { checkKey(key); Node node = main.nextGreater(main.lookup((Comparable) key, VALUE), VALUE); return (node == null ? null : node.getValue()); } public V previousKey(V key) { checkKey(key); Node node = main.nextSmaller(main.lookup((Comparable) key, VALUE), VALUE); return (node == null ? null : node.getValue()); } public K put(final V key, final K value) { return main.doPutByValue(value, key); } public void putAll(Map map) { Iterator it = map.entrySet().iterator(); while (it.hasNext()) { Map.Entry entry = (Map.Entry) it.next(); put((V) entry.getKey(), (K) entry.getValue()); } } public K remove(final Object key) { return main.removeValue((V) key); } public V removeValue(final Object value) { return main.remove(value); } public void clear() { main.clear(); } public Set keySet() { if (keySet == null) { keySet = new View(main, VALUE, VALUE); } return keySet; } public Set values() { if (valuesSet == null) { valuesSet = new View(main, VALUE, KEY); } return valuesSet; } public Set> entrySet() { if (entrySet == null) { return new EntryView(main, VALUE, INVERSEMAPENTRY); } return entrySet; } public MapIterator mapIterator() { if (isEmpty()) { return EmptyOrderedMapIterator.INSTANCE; } return new ViewMapIterator(main, VALUE); } public OrderedMapIterator orderedMapIterator() { if (isEmpty()) { return EmptyOrderedMapIterator.INSTANCE; } return new ViewMapIterator(main, VALUE); } public BidiMap inverseBidiMap() { return main; } public OrderedBidiMap inverseOrderedBidiMap() { return main; } public boolean equals(Object obj) { return main.doEquals(obj, VALUE); } public int hashCode() { return main.doHashCode(VALUE); } public String toString() { return main.doToString(VALUE); } } } collections-generic-4.01/src/java/org/apache/commons/collections15/bidimap/DualHashBidiMap.java0000644000175000017500000000737310464140761032657 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.bidimap; import org.apache.commons.collections15.BidiMap; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.HashMap; import java.util.Map; /** * Implementation of BidiMap that uses two HashMap instances. *

          * Two HashMap instances are used in this class. * This provides fast lookups at the expense of storing two sets of map entries. * Commons Collections would welcome the addition of a direct hash-based * implementation of the BidiMap interface. *

          * NOTE: From Commons Collections 3.1, all subclasses will use HashMap * and the flawed createMap method is ignored. * * @author Matthew Hawthorne * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Id: DualHashBidiMap.java,v 1.1 2005/10/11 17:05:19 pents90 Exp $ * @since Commons Collections 3.0 */ public class DualHashBidiMap extends AbstractDualBidiMap implements Serializable { /** * Ensure serialization compatibility */ private static final long serialVersionUID = 721969328361808L; /** * Creates an empty HashBidiMap. */ public DualHashBidiMap() { super(new HashMap(), new HashMap()); } /** * Constructs a HashBidiMap and copies the mappings from * specified Map. * * @param map the map whose mappings are to be placed in this map */ public DualHashBidiMap(Map map) { super(new HashMap(), new HashMap()); putAll(map); } /** * Constructs a HashBidiMap that decorates the specified maps. * * @param normalMap the normal direction map * @param reverseMap the reverse direction map * @param inverseBidiMap the inverse BidiMap */ protected DualHashBidiMap(Map normalMap, Map reverseMap, BidiMap inverseBidiMap) { super(normalMap, reverseMap, inverseBidiMap); } /** * Creates a new instance of this object. * * @param normalMap the normal direction map * @param reverseMap the reverse direction map * @param inverseBidiMap the inverse BidiMap * @return new bidi map */ protected BidiMap createBidiMap(Map normalMap, Map reverseMap, BidiMap inverseBidiMap) { return new DualHashBidiMap(normalMap, reverseMap, inverseBidiMap); } // Serialization //----------------------------------------------------------------------- private void writeObject(ObjectOutputStream out) throws IOException { out.defaultWriteObject(); out.writeObject(forwardMap); } private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); forwardMap = new HashMap(); inverseMap = new HashMap(); Map map = (Map) in.readObject(); putAll(map); } } collections-generic-4.01/src/java/org/apache/commons/collections15/bidimap/DualTreeBidiMap.java0000644000175000017500000002713510464140760032670 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.bidimap; import org.apache.commons.collections15.*; import org.apache.commons.collections15.map.AbstractSortedMapDecorator; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.*; /** * Implementation of BidiMap that uses two TreeMap instances. *

          * The setValue() method on iterators will succeed only if the new value being set is * not already in the bidimap. *

          * When considering whether to use this class, the {@link TreeBidiMap} class should * also be considered. It implements the interface using a dedicated design, and does * not store each object twice, which can save on memory use. *

          * NOTE: From Commons Collections 3.1, all subclasses will use TreeMap * and the flawed createMap method is ignored. * * @author Matthew Hawthorne * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Id: DualTreeBidiMap.java,v 1.1 2005/10/11 17:05:19 pents90 Exp $ * @since Commons Collections 3.0 */ public class DualTreeBidiMap extends AbstractDualBidiMap implements SortedBidiMap, Serializable { /** * Ensure serialization compatibility */ private static final long serialVersionUID = 721969328361809L; /** * The comparator to use */ protected final Comparator comparator; /** * Creates an empty DualTreeBidiMap */ public DualTreeBidiMap() { super(new TreeMap(), new TreeMap()); this.comparator = null; } public static DualTreeBidiMap createTwoWayBidiMap(Comparator comparator) { return new DualTreeBidiMap(comparator, comparator); } /** * Constructs a DualTreeBidiMap and copies the mappings from * specified Map. * * @param map the map whose mappings are to be placed in this map */ public DualTreeBidiMap(Map map) { super(new TreeMap(), new TreeMap()); putAll(map); this.comparator = null; } /** * Constructs a DualTreeBidiMap using the specified Comparators. * * @param comparator the Comparator */ public DualTreeBidiMap(Comparator comparator, Comparator inverseComparator) { super(new TreeMap(comparator), new TreeMap(inverseComparator)); this.comparator = comparator; } /** * Constructs a DualTreeBidiMap that decorates the specified maps. * * @param normalMap the normal direction map * @param reverseMap the reverse direction map * @param inverseBidiMap the inverse BidiMap */ protected DualTreeBidiMap(Map normalMap, Map reverseMap, BidiMap inverseBidiMap) { super(normalMap, reverseMap, inverseBidiMap); this.comparator = ((SortedMap) normalMap).comparator(); } /** * Creates a new instance of this object. * * @param normalMap the normal direction map * @param reverseMap the reverse direction map * @param inverseMap the inverse BidiMap * @return new bidi map */ protected BidiMap createBidiMap(Map normalMap, Map reverseMap, BidiMap inverseMap) { return new DualTreeBidiMap(normalMap, reverseMap, inverseMap); } //----------------------------------------------------------------------- public Comparator comparator() { return ((SortedMap) forwardMap).comparator(); } public K firstKey() { return ((SortedMap) forwardMap).firstKey(); } public K lastKey() { return ((SortedMap) forwardMap).lastKey(); } public K nextKey(K key) { if (isEmpty()) { return null; } if (forwardMap instanceof OrderedMap) { return ((OrderedMap) forwardMap).nextKey(key); } SortedMap sm = (SortedMap) forwardMap; Iterator it = sm.tailMap(key).keySet().iterator(); it.next(); if (it.hasNext()) { return it.next(); } return null; } public K previousKey(K key) { if (isEmpty()) { return null; } if (forwardMap instanceof OrderedMap) { return ((OrderedMap) forwardMap).previousKey(key); } SortedMap sm = (SortedMap) forwardMap; SortedMap hm = sm.headMap(key); if (hm.isEmpty()) { return null; } return hm.lastKey(); } //----------------------------------------------------------------------- /** * Obtains an ordered map iterator. *

          * This implementation copies the elements to an ArrayList in order to * provide the forward/backward behaviour. * * @return a new ordered map iterator */ public OrderedMapIterator orderedMapIterator() { return new BidiOrderedMapIterator(this); } public SortedBidiMap inverseSortedBidiMap() { return (SortedBidiMap) inverseBidiMap(); } public OrderedBidiMap inverseOrderedBidiMap() { return (OrderedBidiMap) inverseBidiMap(); } //----------------------------------------------------------------------- public SortedMap headMap(K toKey) { SortedMap sub = ((SortedMap) forwardMap).headMap(toKey); return new ViewMap(this, sub); } public SortedMap tailMap(K fromKey) { SortedMap sub = ((SortedMap) forwardMap).tailMap(fromKey); return new ViewMap(this, sub); } public SortedMap subMap(K fromKey, K toKey) { SortedMap sub = ((SortedMap) forwardMap).subMap(fromKey, toKey); return new ViewMap(this, sub); } //----------------------------------------------------------------------- /** * Internal sorted map view. */ protected static class ViewMap extends AbstractSortedMapDecorator { /** * The parent bidi map. */ final DualTreeBidiMap bidi; /** * Constructor. * * @param bidi the parent bidi map * @param sm the subMap sorted map */ protected ViewMap(DualTreeBidiMap bidi, SortedMap sm) { // the implementation is not great here... // use the forwardMap as the filtered map, but inverseMap as the full map // this forces containsValue and clear to be overridden super((SortedMap) bidi.createBidiMap(sm, bidi.inverseMap, bidi.inverseBidiMap)); this.bidi = (DualTreeBidiMap) map; } public boolean containsValue(Object value) { // override as default implementation jumps to [1] return bidi.forwardMap.containsValue(value); } public void clear() { // override as default implementation jumps to [1] for (Iterator it = keySet().iterator(); it.hasNext();) { it.next(); it.remove(); } } public SortedMap headMap(K toKey) { return new ViewMap(bidi, super.headMap(toKey)); } public SortedMap tailMap(K fromKey) { return new ViewMap(bidi, super.tailMap(fromKey)); } public SortedMap subMap(K fromKey, K toKey) { return new ViewMap(bidi, super.subMap(fromKey, toKey)); } } //----------------------------------------------------------------------- /** * Inner class MapIterator. */ protected static class BidiOrderedMapIterator implements OrderedMapIterator, ResettableIterator { /** * The parent map */ protected final AbstractDualBidiMap parent; /** * The iterator being decorated */ protected ListIterator> iterator; /** * The last returned entry */ private Map.Entry last = null; /** * Constructor. * * @param parent the parent map */ protected BidiOrderedMapIterator(AbstractDualBidiMap parent) { super(); this.parent = parent; iterator = new ArrayList>(parent.entrySet()).listIterator(); } public boolean hasNext() { return iterator.hasNext(); } public K next() { last = iterator.next(); return last.getKey(); } public boolean hasPrevious() { return iterator.hasPrevious(); } public K previous() { last = iterator.previous(); return last.getKey(); } public void remove() { iterator.remove(); parent.remove(last.getKey()); last = null; } public K getKey() { if (last == null) { throw new IllegalStateException("Iterator getKey() can only be called after next() and before remove()"); } return last.getKey(); } public V getValue() { if (last == null) { throw new IllegalStateException("Iterator getValue() can only be called after next() and before remove()"); } return last.getValue(); } public V setValue(V value) { if (last == null) { throw new IllegalStateException("Iterator setValue() can only be called after next() and before remove()"); } if (parent.inverseMap.containsKey(value) && parent.inverseMap.get(value) != last.getKey()) { throw new IllegalArgumentException("Cannot use setValue() when the object being set is already in the map"); } return parent.put(last.getKey(), value); } public void reset() { iterator = new ArrayList>(parent.entrySet()).listIterator(); last = null; } public String toString() { if (last != null) { return "MapIterator[" + getKey() + "=" + getValue() + "]"; } else { return "MapIterator[]"; } } } // Serialization //----------------------------------------------------------------------- private void writeObject(ObjectOutputStream out) throws IOException { out.defaultWriteObject(); out.writeObject(forwardMap); } private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); forwardMap = new TreeMap(comparator); inverseMap = new TreeMap(); Map map = (Map) in.readObject(); putAll(map); } } ././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootcollections-generic-4.01/src/java/org/apache/commons/collections15/bidimap/UnmodifiableOrderedBidiMap.javacollections-generic-4.01/src/java/org/apache/commons/collections15/bidimap/UnmodifiableOrderedBidiMa0000644000175000017500000001006310464140756033763 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.bidimap; import org.apache.commons.collections15.*; import org.apache.commons.collections15.iterators.UnmodifiableOrderedMapIterator; import org.apache.commons.collections15.map.UnmodifiableEntrySet; import org.apache.commons.collections15.set.UnmodifiableSet; import java.util.Map; import java.util.Set; /** * Decorates another OrderedBidiMap to ensure it can't be altered. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:19 $ * @since Commons Collections 3.0 */ public final class UnmodifiableOrderedBidiMap extends AbstractOrderedBidiMapDecorator implements Unmodifiable { /** * The inverse unmodifiable map */ private UnmodifiableOrderedBidiMap inverse; /** * Factory method to create an unmodifiable map. *

          * If the map passed in is already unmodifiable, it is returned. * * @param map the map to decorate, must not be null * @return an unmodifiable OrderedBidiMap * @throws IllegalArgumentException if map is null */ public static OrderedBidiMap decorate(OrderedBidiMap map) { if (map instanceof Unmodifiable) { return map; } return new UnmodifiableOrderedBidiMap(map); } //----------------------------------------------------------------------- /** * Constructor that wraps (not copies). * * @param map the map to decorate, must not be null * @throws IllegalArgumentException if map is null */ private UnmodifiableOrderedBidiMap(OrderedBidiMap map) { super(map); } //----------------------------------------------------------------------- public void clear() { throw new UnsupportedOperationException(); } public V put(K key, V value) { throw new UnsupportedOperationException(); } public void putAll(Map mapToCopy) { throw new UnsupportedOperationException(); } public V remove(Object key) { throw new UnsupportedOperationException(); } public Set> entrySet() { Set> set = super.entrySet(); return UnmodifiableEntrySet.decorate(set); } public Set keySet() { Set set = super.keySet(); return UnmodifiableSet.decorate(set); } public Set values() { Set coll = super.values(); return UnmodifiableSet.decorate(coll); } //----------------------------------------------------------------------- public K removeValue(Object value) { throw new UnsupportedOperationException(); } public MapIterator mapIterator() { return orderedMapIterator(); } public BidiMap inverseBidiMap() { return inverseOrderedBidiMap(); } //----------------------------------------------------------------------- public OrderedMapIterator orderedMapIterator() { OrderedMapIterator it = getOrderedBidiMap().orderedMapIterator(); return UnmodifiableOrderedMapIterator.decorate(it); } public OrderedBidiMap inverseOrderedBidiMap() { if (inverse == null) { inverse = new UnmodifiableOrderedBidiMap(getOrderedBidiMap().inverseOrderedBidiMap()); inverse.inverse = this; } return inverse; } } collections-generic-4.01/src/java/org/apache/commons/collections15/bidimap/UnmodifiableBidiMap.java0000644000175000017500000000742110464140764033561 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.bidimap; import org.apache.commons.collections15.BidiMap; import org.apache.commons.collections15.MapIterator; import org.apache.commons.collections15.Unmodifiable; import org.apache.commons.collections15.iterators.UnmodifiableMapIterator; import org.apache.commons.collections15.map.UnmodifiableEntrySet; import org.apache.commons.collections15.set.UnmodifiableSet; import java.util.Map; import java.util.Set; /** * Decorates another BidiMap to ensure it can't be altered. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:19 $ * @since Commons Collections 3.0 */ public final class UnmodifiableBidiMap extends AbstractBidiMapDecorator implements Unmodifiable { /** * The inverse unmodifiable map */ private UnmodifiableBidiMap inverse; /** * Factory method to create an unmodifiable map. *

          * If the map passed in is already unmodifiable, it is returned. * * @param map the map to decorate, must not be null * @return an unmodifiable BidiMap * @throws IllegalArgumentException if map is null */ public static BidiMap decorate(BidiMap map) { if (map instanceof Unmodifiable) { return map; } return new UnmodifiableBidiMap(map); } //----------------------------------------------------------------------- /** * Constructor that wraps (not copies). * * @param map the map to decorate, must not be null * @throws IllegalArgumentException if map is null */ private UnmodifiableBidiMap(BidiMap map) { super(map); } //----------------------------------------------------------------------- public void clear() { throw new UnsupportedOperationException(); } public V put(K key, V value) { throw new UnsupportedOperationException(); } public void putAll(Map mapToCopy) { throw new UnsupportedOperationException(); } public V remove(Object key) { throw new UnsupportedOperationException(); } public Set> entrySet() { Set> set = super.entrySet(); return UnmodifiableEntrySet.decorate(set); } public Set keySet() { Set set = super.keySet(); return UnmodifiableSet.decorate(set); } public Set values() { Set coll = super.values(); return (Set) UnmodifiableSet.decorate(coll); } //----------------------------------------------------------------------- public K removeValue(Object value) { throw new UnsupportedOperationException(); } public MapIterator mapIterator() { MapIterator it = getBidiMap().mapIterator(); return UnmodifiableMapIterator.decorate(it); } public BidiMap inverseBidiMap() { if (inverse == null) { inverse = new UnmodifiableBidiMap(getBidiMap().inverseBidiMap()); inverse.inverse = this; } return inverse; } } collections-generic-4.01/src/java/org/apache/commons/collections15/bidimap/AbstractDualBidiMap.java0000644000175000017500000005557410464140764033550 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.bidimap; import org.apache.commons.collections15.BidiMap; import org.apache.commons.collections15.MapIterator; import org.apache.commons.collections15.ResettableIterator; import org.apache.commons.collections15.collection.AbstractCollectionDecorator; import org.apache.commons.collections15.iterators.AbstractIteratorDecorator; import org.apache.commons.collections15.keyvalue.AbstractMapEntryDecorator; import java.util.Collection; import java.util.Iterator; import java.util.Map; import java.util.Set; /** * Abstract BidiMap implemented using two maps. *

          * An implementation can be written simply by implementing the * createMap method. * * @author Matthew Hawthorne * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Id: AbstractDualBidiMap.java,v 1.1 2005/10/11 17:05:19 pents90 Exp $ * @see DualHashBidiMap * @see DualTreeBidiMap * @since Commons Collections 3.0 */ public abstract class AbstractDualBidiMap implements BidiMap { /** * Delegate maps. The first map contains standard entries, and the * second contains inverses. */ protected transient Map forwardMap; protected transient Map inverseMap; /** * Inverse view of this map. */ protected transient BidiMap inverseBidiMap = null; /** * View of the keys. */ protected transient Set keySet = null; /** * View of the values. */ protected transient Set values = null; /** * View of the entries. */ protected transient Set> entrySet = null; /** * Creates an empty map, initialised by createMap. *

          * This constructor remains in place for deserialization. * All other usage is deprecated in favour of * {@link #AbstractDualBidiMap(Map, Map)}. * * @deprecated should not be used. */ protected AbstractDualBidiMap() { super(); forwardMap = createMap(); inverseMap = createMap(); } /** * Creates an empty map using the two maps specified as storage. *

          * The two maps must be a matching pair, normal and reverse. * They will typically both be empty. *

          * Neither map is validated, so nulls may be passed in. * If you choose to do this then the subclass constructor must populate * the maps[] instance variable itself. * * @param normalMap the normal direction map * @param reverseMap the reverse direction map * @since Commons Collections 3.1 */ protected AbstractDualBidiMap(Map normalMap, Map reverseMap) { super(); forwardMap = normalMap; inverseMap = reverseMap; } /** * Constructs a map that decorates the specified maps, * used by the subclass createBidiMap implementation. * * @param normalMap the normal direction map * @param reverseMap the reverse direction map * @param inverseBidiMap the inverse BidiMap */ protected AbstractDualBidiMap(Map normalMap, Map reverseMap, BidiMap inverseBidiMap) { super(); forwardMap = normalMap; inverseMap = reverseMap; this.inverseBidiMap = inverseBidiMap; } /** * Creates a new instance of the map used by the subclass to store data. *

          * This design is deeply flawed and has been deprecated. * It relied on subclass data being used during a superclass constructor. * * @return the map to be used for internal storage * @deprecated For constructors, use the new two map constructor. * For deserialization, populate the maps array directly in readObject. */ protected Map createMap() { return null; } /** * Creates a new instance of the subclass. * * @param normalMap the normal direction map * @param reverseMap the reverse direction map * @param inverseMap this map, which is the inverse in the new map * @return the inverse map */ protected abstract BidiMap createBidiMap(Map normalMap, Map reverseMap, BidiMap inverseMap); // Map delegation //----------------------------------------------------------------------- public V get(Object key) { return forwardMap.get(key); } public int size() { return forwardMap.size(); } public boolean isEmpty() { return forwardMap.isEmpty(); } public boolean containsKey(Object key) { return forwardMap.containsKey(key); } public boolean equals(Object obj) { return forwardMap.equals(obj); } public int hashCode() { return forwardMap.hashCode(); } public String toString() { return forwardMap.toString(); } // BidiMap changes //----------------------------------------------------------------------- public V put(K key, V value) { if (forwardMap.containsKey(key)) { inverseMap.remove(forwardMap.get(key)); } if (inverseMap.containsKey(value)) { forwardMap.remove(inverseMap.get(value)); } final V obj = forwardMap.put(key, value); inverseMap.put(value, key); return obj; } public void putAll(Map map) { for (Iterator it = map.entrySet().iterator(); it.hasNext();) { Map.Entry entry = (Map.Entry) it.next(); put((K) entry.getKey(), (V) entry.getValue()); } } public V remove(Object key) { V value = null; if (forwardMap.containsKey(key)) { value = forwardMap.remove(key); inverseMap.remove(value); } return value; } public void clear() { forwardMap.clear(); inverseMap.clear(); } public boolean containsValue(Object value) { return inverseMap.containsKey(value); } // BidiMap //----------------------------------------------------------------------- /** * Obtains a MapIterator over the map. * The iterator implements ResetableMapIterator. * This implementation relies on the entrySet iterator. *

          * The setValue() methods only allow a new value to be set. * If the value being set is already in the map, an IllegalArgumentException * is thrown (as setValue cannot change the size of the map). * * @return a map iterator */ public MapIterator mapIterator() { return new BidiMapIterator(this); } public K getKey(Object value) { return inverseMap.get(value); } public K removeValue(Object value) { K key = null; if (inverseMap.containsKey(value)) { key = inverseMap.remove(value); forwardMap.remove(key); } return key; } public BidiMap inverseBidiMap() { if (inverseBidiMap == null) { inverseBidiMap = createBidiMap(inverseMap, forwardMap, this); } return inverseBidiMap; } // Map views //----------------------------------------------------------------------- /** * Gets a keySet view of the map. * Changes made on the view are reflected in the map. * The set supports remove and clear but not add. * * @return the keySet view */ public Set keySet() { if (keySet == null) { keySet = new KeySet(this); } return keySet; } /** * Creates a key set iterator. * Subclasses can override this to return iterators with different properties. * * @param iterator the iterator to decorate * @return the keySet iterator */ protected Iterator createKeySetIterator(Iterator iterator) { return new KeySetIterator(iterator, this); } /** * Gets a values view of the map. * Changes made on the view are reflected in the map. * The set supports remove and clear but not add. * * @return the values view */ public Set values() { if (values == null) { values = new Values(this); } return values; } /** * Creates a values iterator. * Subclasses can override this to return iterators with different properties. * * @param iterator the iterator to decorate * @return the values iterator */ protected Iterator createValuesIterator(Iterator iterator) { return new ValuesIterator(iterator, this); } /** * Gets an entrySet view of the map. * Changes made on the set are reflected in the map. * The set supports remove and clear but not add. *

          * The Map Entry setValue() method only allow a new value to be set. * If the value being set is already in the map, an IllegalArgumentException * is thrown (as setValue cannot change the size of the map). * * @return the entrySet view */ public Set> entrySet() { if (entrySet == null) { entrySet = new EntrySet(this); } return entrySet; } /** * Creates an entry set iterator. * Subclasses can override this to return iterators with different properties. * * @param iterator the iterator to decorate * @return the entrySet iterator */ protected Iterator> createEntrySetIterator(Iterator> iterator) { return new EntrySetIterator(iterator, this); } //----------------------------------------------------------------------- /** * Inner class View. */ protected static abstract class View extends AbstractCollectionDecorator { /** * The parent map */ protected final AbstractDualBidiMap parent; /** * Constructs a new view of the BidiMap. * * @param coll the collection view being decorated * @param parent the parent BidiMap */ protected View(Collection coll, AbstractDualBidiMap parent) { super(coll); this.parent = parent; } public boolean removeAll(Collection coll) { if (parent.isEmpty() || coll.isEmpty()) { return false; } boolean modified = false; Iterator it = iterator(); while (it.hasNext()) { if (coll.contains(it.next())) { it.remove(); modified = true; } } return modified; } public boolean retainAll(Collection coll) { if (parent.isEmpty()) { return false; } if (coll.isEmpty()) { parent.clear(); return true; } boolean modified = false; Iterator it = iterator(); while (it.hasNext()) { if (coll.contains(it.next()) == false) { it.remove(); modified = true; } } return modified; } public void clear() { parent.clear(); } } //----------------------------------------------------------------------- /** * Inner class KeySet. */ protected static class KeySet extends View implements Set { /** * Constructs a new view of the BidiMap. * * @param parent the parent BidiMap */ protected KeySet(AbstractDualBidiMap parent) { super(parent.forwardMap.keySet(), parent); } public Iterator iterator() { return parent.createKeySetIterator(super.iterator()); } public boolean contains(Object key) { return parent.forwardMap.containsKey(key); } public boolean remove(Object key) { if (parent.forwardMap.containsKey(key)) { Object value = parent.forwardMap.remove(key); parent.inverseMap.remove(value); return true; } return false; } } /** * Inner class KeySetIterator. */ protected static class KeySetIterator extends AbstractIteratorDecorator { /** * The parent map */ protected final AbstractDualBidiMap parent; /** * The last returned key */ protected K lastKey = null; /** * Whether remove is allowed at present */ protected boolean canRemove = false; /** * Constructor. * * @param iterator the iterator to decorate * @param parent the parent map */ protected KeySetIterator(Iterator iterator, AbstractDualBidiMap parent) { super(iterator); this.parent = parent; } public K next() { lastKey = super.next(); canRemove = true; return lastKey; } public void remove() { if (canRemove == false) { throw new IllegalStateException("Iterator remove() can only be called once after next()"); } Object value = parent.forwardMap.get(lastKey); super.remove(); parent.inverseMap.remove(value); lastKey = null; canRemove = false; } } //----------------------------------------------------------------------- /** * Inner class Values. */ protected static class Values extends View implements Set { /** * Constructs a new view of the BidiMap. * * @param parent the parent BidiMap */ protected Values(AbstractDualBidiMap parent) { super(parent.forwardMap.values(), parent); } public Iterator iterator() { return parent.createValuesIterator(super.iterator()); } public boolean contains(Object value) { return parent.inverseMap.containsKey(value); } public boolean remove(Object value) { if (parent.inverseMap.containsKey(value)) { Object key = parent.inverseMap.remove(value); parent.forwardMap.remove(key); return true; } return false; } } /** * Inner class ValuesIterator. */ protected static class ValuesIterator extends AbstractIteratorDecorator { /** * The parent map */ protected final AbstractDualBidiMap parent; /** * The last returned value */ protected V lastValue = null; /** * Whether remove is allowed at present */ protected boolean canRemove = false; /** * Constructor. * * @param iterator the iterator to decorate * @param parent the parent map */ protected ValuesIterator(Iterator iterator, AbstractDualBidiMap parent) { super(iterator); this.parent = parent; } public V next() { lastValue = super.next(); canRemove = true; return lastValue; } public void remove() { if (canRemove == false) { throw new IllegalStateException("Iterator remove() can only be called once after next()"); } super.remove(); // removes from forwardMap parent.inverseMap.remove(lastValue); lastValue = null; canRemove = false; } } //----------------------------------------------------------------------- /** * Inner class EntrySet. */ protected static class EntrySet extends View> implements Set> { /** * Constructs a new view of the BidiMap. * * @param parent the parent BidiMap */ protected EntrySet(AbstractDualBidiMap parent) { super(parent.forwardMap.entrySet(), parent); } public Iterator> iterator() { return parent.createEntrySetIterator(super.iterator()); } public boolean remove(Object obj) { if (obj instanceof Map.Entry == false) { return false; } Map.Entry entry = (Map.Entry) obj; Object key = entry.getKey(); if (parent.containsKey(key)) { Object value = parent.forwardMap.get(key); if (value == null ? entry.getValue() == null : value.equals(entry.getValue())) { parent.forwardMap.remove(key); parent.inverseMap.remove(value); return true; } } return false; } } /** * Inner class EntrySetIterator. */ protected static class EntrySetIterator extends AbstractIteratorDecorator> { /** * The parent map */ protected final AbstractDualBidiMap parent; /** * The last returned entry */ protected Map.Entry last = null; /** * Whether remove is allowed at present */ protected boolean canRemove = false; /** * Constructor. * * @param iterator the iterator to decorate * @param parent the parent map */ protected EntrySetIterator(Iterator> iterator, AbstractDualBidiMap parent) { super(iterator); this.parent = parent; } public Map.Entry next() { last = new MapEntry(super.next(), parent); canRemove = true; return last; } public void remove() { if (canRemove == false) { throw new IllegalStateException("Iterator remove() can only be called once after next()"); } // store value as remove may change the entry in the decorator (eg.TreeMap) Object value = last.getValue(); super.remove(); parent.inverseMap.remove(value); last = null; canRemove = false; } } /** * Inner class MapEntry. */ protected static class MapEntry extends AbstractMapEntryDecorator { /** * The parent map */ protected final AbstractDualBidiMap parent; /** * Constructor. * * @param entry the entry to decorate * @param parent the parent map */ protected MapEntry(Map.Entry entry, AbstractDualBidiMap parent) { super(entry); this.parent = parent; } public V setValue(V value) { K key = MapEntry.this.getKey(); if (parent.inverseMap.containsKey(value) && parent.inverseMap.get(value) != key) { throw new IllegalArgumentException("Cannot use setValue() when the object being set is already in the map"); } parent.put(key, value); final V oldValue = super.setValue(value); return oldValue; } } /** * Inner class MapIterator. */ protected static class BidiMapIterator implements MapIterator, ResettableIterator { /** * The parent map */ protected final AbstractDualBidiMap parent; /** * The iterator being wrapped */ protected Iterator> iterator; /** * The last returned entry */ protected Map.Entry last = null; /** * Whether remove is allowed at present */ protected boolean canRemove = false; /** * Constructor. * * @param parent the parent map */ protected BidiMapIterator(AbstractDualBidiMap parent) { super(); this.parent = parent; this.iterator = parent.forwardMap.entrySet().iterator(); } public boolean hasNext() { return iterator.hasNext(); } public K next() { last = iterator.next(); canRemove = true; return last.getKey(); } public void remove() { if (canRemove == false) { throw new IllegalStateException("Iterator remove() can only be called once after next()"); } // store value as remove may change the entry in the decorator (eg.TreeMap) V value = last.getValue(); iterator.remove(); parent.inverseMap.remove(value); last = null; canRemove = false; } public K getKey() { if (last == null) { throw new IllegalStateException("Iterator getKey() can only be called after next() and before remove()"); } return last.getKey(); } public V getValue() { if (last == null) { throw new IllegalStateException("Iterator getValue() can only be called after next() and before remove()"); } return last.getValue(); } public V setValue(V value) { if (last == null) { throw new IllegalStateException("Iterator setValue() can only be called after next() and before remove()"); } if (parent.inverseMap.containsKey(value) && parent.inverseMap.get(value) != last.getKey()) { throw new IllegalArgumentException("Cannot use setValue() when the object being set is already in the map"); } return parent.put(last.getKey(), value); } public void reset() { iterator = parent.forwardMap.entrySet().iterator(); last = null; canRemove = false; } public String toString() { if (last != null) { return "MapIterator[" + getKey() + "=" + getValue() + "]"; } else { return "MapIterator[]"; } } } } ././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootcollections-generic-4.01/src/java/org/apache/commons/collections15/bidimap/UnmodifiableSortedBidiMap.javacollections-generic-4.01/src/java/org/apache/commons/collections15/bidimap/UnmodifiableSortedBidiMap0000644000175000017500000001150510464140756034021 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.bidimap; import org.apache.commons.collections15.*; import org.apache.commons.collections15.iterators.UnmodifiableOrderedMapIterator; import org.apache.commons.collections15.map.UnmodifiableEntrySet; import org.apache.commons.collections15.map.UnmodifiableSortedMap; import org.apache.commons.collections15.set.UnmodifiableSet; import java.util.Map; import java.util.Set; import java.util.SortedMap; /** * Decorates another SortedBidiMap to ensure it can't be altered. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:19 $ * @since Commons Collections 3.0 */ public final class UnmodifiableSortedBidiMap extends AbstractSortedBidiMapDecorator implements Unmodifiable { /** * The inverse unmodifiable map */ private UnmodifiableSortedBidiMap inverse; /** * Factory method to create an unmodifiable map. *

          * If the map passed in is already unmodifiable, it is returned. * * @param map the map to decorate, must not be null * @return an unmodifiable SortedBidiMap * @throws IllegalArgumentException if map is null */ public static SortedBidiMap decorate(SortedBidiMap map) { if (map instanceof Unmodifiable) { return map; } return new UnmodifiableSortedBidiMap(map); } //----------------------------------------------------------------------- /** * Constructor that wraps (not copies). * * @param map the map to decorate, must not be null * @throws IllegalArgumentException if map is null */ private UnmodifiableSortedBidiMap(SortedBidiMap map) { super(map); } //----------------------------------------------------------------------- public void clear() { throw new UnsupportedOperationException(); } public V put(K key, V value) { throw new UnsupportedOperationException(); } public void putAll(Map mapToCopy) { throw new UnsupportedOperationException(); } public V remove(Object key) { throw new UnsupportedOperationException(); } public Set> entrySet() { Set> set = super.entrySet(); return UnmodifiableEntrySet.decorate(set); } public Set keySet() { Set set = super.keySet(); return UnmodifiableSet.decorate(set); } public Set values() { Set coll = super.values(); return UnmodifiableSet.decorate(coll); } //----------------------------------------------------------------------- public K removeValue(Object value) { throw new UnsupportedOperationException(); } public MapIterator mapIterator() { return orderedMapIterator(); } public BidiMap inverseBidiMap() { return inverseSortedBidiMap(); } //----------------------------------------------------------------------- public OrderedMapIterator orderedMapIterator() { OrderedMapIterator it = getSortedBidiMap().orderedMapIterator(); return UnmodifiableOrderedMapIterator.decorate(it); } public OrderedBidiMap inverseOrderedBidiMap() { return inverseSortedBidiMap(); } //----------------------------------------------------------------------- public SortedBidiMap inverseSortedBidiMap() { if (inverse == null) { inverse = new UnmodifiableSortedBidiMap(getSortedBidiMap().inverseSortedBidiMap()); inverse.inverse = this; } return inverse; } public SortedMap subMap(K fromKey, K toKey) { SortedMap sm = getSortedBidiMap().subMap(fromKey, toKey); return UnmodifiableSortedMap.decorate(sm); } public SortedMap headMap(K toKey) { SortedMap sm = getSortedBidiMap().headMap(toKey); return UnmodifiableSortedMap.decorate(sm); } public SortedMap tailMap(K fromKey) { SortedMap sm = getSortedBidiMap().tailMap(fromKey); return UnmodifiableSortedMap.decorate(sm); } } collections-generic-4.01/src/java/org/apache/commons/collections15/bidimap/package.html0000644000175000017500000000403310464140761031344 0ustar giovannigiovanni

          This package contains implementations of the {@link org.apache.commons.collections.BidiMap BidiMap}, {@link org.apache.commons.collections.OrderedBidiMap OrderedBidiMap} and {@link org.apache.commons.collections.SortedBidiMap SortedBidiMap} interfaces. A BidiMap is an extension to Map that allows keys and values to be looked up with equal ease. One example usage is a system communicating to a legacy datasource that must convert codes from the new format to the old format and vice versa.

          The following implementations are provided in the package:

          • DualHashBidiMap - uses two HashMaps to implement BidiMap
          • DualTreeBidiMap - uses two TreeMaps to implement SortedBidiMap
          • TreeBidiMap - red-black tree implementation of OrderedBidiMap

          The following decorators are provided in the package:

          • Unmodifiable - ensures the map cannot be altered
          collections-generic-4.01/src/java/org/apache/commons/collections15/multimap/0000755000175000017500000000000011664401370027305 5ustar giovannigiovannicollections-generic-4.01/src/java/org/apache/commons/collections15/multimap/MultiHashMap.java0000644000175000017500000004057310464140757032523 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.multimap; import org.apache.commons.collections15.iterators.EmptyIterator; import org.apache.commons.collections15.MultiMap; import java.io.IOException; import java.io.ObjectInputStream; import java.io.Serializable; import java.util.*; /** * MultiHashMap is the default implementation of the * {@link org.apache.commons.collections15.MultiMap MultiMap} interface. *

          * A MultiMap is like a Map, but with slightly different semantics. * Putting a value into the map will add the value to a Collection at that key. * Getting a value will return a Collection, holding all the values put to that key. *

          * This implementation uses an ArrayList as the collection. * The internal storage list is made available without cloning via the * get(Object) and entrySet() methods. * The implementation returns null when there are no values mapped to a key. *

          * For example: *

           * Number key = new Integer(5);
           * MultiMap<Number,String> mhm = new MultiHashMap<Number,String>();
           * mhm.put(key, "A");
           * mhm.put(key, "B");
           * mhm.put(key, "C");
           * Collection<String> coll = mhm.get(key);
          *

          * list will be a list containing "A", "B", "C". * * @author Christopher Berry * @author James Strachan * @author Steve Downey * @author Stephen Colebourne * @author Julien Buret * @author Matt Hall, John Watkinson, Serhiy Yevtushenko * @version $Revision: 1.2 $ $Date: 2006/06/08 15:19:55 $ * @since Commons Collections 2.0 */ public class MultiHashMap implements MultiMap, Serializable, Cloneable { // backed values collection private transient Collection values = null; // compatibility with commons-collection releases 2.0/2.1 private static final long serialVersionUID = 1943563828307035349L; private HashMap> internalMap; /** * Constructor. */ public MultiHashMap() { internalMap = new HashMap>(); } /** * Constructor. * * @param initialCapacity the initial map capacity */ public MultiHashMap(int initialCapacity) { internalMap = new HashMap>(initialCapacity); } /** * Constructor. * * @param initialCapacity the initial map capacity * @param loadFactor the amount 0.0-1.0 at which to resize the map */ public MultiHashMap(int initialCapacity, float loadFactor) { internalMap = new HashMap>(initialCapacity, loadFactor); } /** * Constructor that copies the input map creating an independent copy. *

          * The values are not cloned. *

          * * @param mapToCopy a Map to copy */ public MultiHashMap(Map mapToCopy) { // be careful of JDK 1.3 vs 1.4 differences internalMap = new HashMap>((int) (mapToCopy.size() * 1.4f)); putAll(mapToCopy); } /** * Constructor that copies the input MultiMap creating an independent copy. *

          * Each internal collection is also cloned. *

          * NOTE: From Commons Collections 3.1 this method correctly copies a MultiMap * to form a truly independent new map. * * @param mapToCopy a Map to copy */ public MultiHashMap(MultiMap mapToCopy) { internalMap = new HashMap>((int) (mapToCopy.size() * 1.4f)); for (Iterator>> it = mapToCopy.entrySet().iterator(); it.hasNext();) { Map.Entry> entry = it.next(); Collection coll = entry.getValue(); Collection newColl = createCollection(coll); internalMap.put(entry.getKey(), newColl); } } /** * Read the object during deserialization. */ private void readObject(ObjectInputStream s) throws IOException, ClassNotFoundException { // This method is needed because the 1.2/1.3 Java deserialisation called // put and thus messed up that method // default read object s.defaultReadObject(); // problem only with jvm <1.4 String version = "1.2"; try { version = System.getProperty("java.version"); } catch (SecurityException ex) { // ignore and treat as 1.2/1.3 } if (version.startsWith("1.2") || version.startsWith("1.3")) { for (Iterator>> iterator = entrySet().iterator(); iterator.hasNext();) { Map.Entry> entry = iterator.next(); // put has created a extra collection level, remove it internalMap.put(entry.getKey(), entry.getValue()); } } } //----------------------------------------------------------------------- /** * Gets the total size of the map by counting all the values. * * @return the total size of the map counting all values * @since Commons Collections 3.1 */ public int totalSize() { int total = 0; Collection> values = internalMap.values(); for (Iterator> it = values.iterator(); it.hasNext();) { Collection coll = it.next(); total += coll.size(); } return total; } /** * Gets the collection mapped to the specified key. * This method is a convenience method to typecast the result of get(key). * * @param key the key to retrieve * @return the collection mapped to the key, null if no mapping * @since Commons Collections 3.1 */ public Collection getCollection(Object key) { return internalMap.get(key); } /** * Gets the size of the collection mapped to the specified key. * * @param key the key to get size for * @return the size of the collection at the key, zero if key not in map * @since Commons Collections 3.1 */ public int size(Object key) { Collection coll = getCollection(key); if (coll == null) { return 0; } return coll.size(); } /** * Gets an iterator for the collection mapped to the specified key. * * @param key the key to get an iterator for * @return the iterator of the collection at the key, empty iterator if key not in map * @since Commons Collections 3.1 */ public Iterator iterator(Object key) { Collection coll = getCollection(key); if (coll == null) { return EmptyIterator.INSTANCE; } return coll.iterator(); } /** * Adds the value to the collection associated with the specified key. *

          * Unlike a normal Map the previous value is not replaced. * Instead the new value is added to the collection stored against the key. * * @param key the key to store against * @param value the value to add to the collection at the key * @return the value added if the map changed and null if the map did not change */ public V put(K key, V value) { // NOTE:: put is called during deserialization in JDK < 1.4 !!!!!! // so we must have a readObject() Collection coll = getCollection(key); if (coll == null) { coll = createCollection(null); internalMap.put(key, coll); } boolean results = coll.add(value); return results ? value : null; } /** * Adds a collection of values to the collection associated with the specified key. * * @param key the key to store against * @param values the values to add to the collection at the key, null ignored * @return true if this map changed * @since Commons Collections 3.1 */ public boolean putAll(K key, Collection values) { if (values == null || values.size() == 0) { return false; } Collection coll = getCollection(key); if (coll == null) { coll = createCollection(values); if (coll.size() == 0) { return false; } internalMap.put(key, coll); return true; } else { return coll.addAll(values); } } /** * Checks whether the map contains the value specified. *

          * This checks all collections15 against all keys for the value, and thus could be slow. * * @param value the value to search for * @return true if the map contains the value */ public boolean containsValue(Object value) { Set>> pairs = internalMap.entrySet(); if (pairs == null) { return false; } Iterator>> pairsIterator = pairs.iterator(); while (pairsIterator.hasNext()) { Map.Entry> keyValuePair = pairsIterator.next(); Collection coll = keyValuePair.getValue(); if (coll.contains(value)) { return true; } } return false; } /** * Checks whether the collection at the specified key contains the value. * * @param value the value to search for * @return true if the map contains the value * @since Commons Collections 3.1 */ public boolean containsValue(Object key, Object value) { Collection coll = getCollection(key); if (coll == null) { return false; } return coll.contains(value); } /** * Removes a specific value from map. *

          * The item is removed from the collection mapped to the specified key. * Other values attached to that key are unaffected. *

          * If the last value for a key is removed, null will be returned * from a subsequant get(key). * * @param key the key to remove from * @param item the value to remove * @return the value removed (which was passed in), null if nothing removed */ public V remove(Object key, Object item) { Collection valuesForKey = getCollection(key); if (valuesForKey == null) { return null; } valuesForKey.remove(item); // remove the list if it is now empty // (saves space, and allows equals to work) if (valuesForKey.isEmpty()) { remove(key); } return (V)item; } /** * Clear the map. *

          * This clears each collection in the map, and so may be slow. */ public void clear() { // For gc, clear each list in the map Set>> pairs = internalMap.entrySet(); Iterator>> pairsIterator = pairs.iterator(); while (pairsIterator.hasNext()) { Map.Entry> keyValuePair = pairsIterator.next(); Collection coll = keyValuePair.getValue(); coll.clear(); } internalMap.clear(); } public int size() { return internalMap.size(); } public Collection get(Object key) { return internalMap.get(key); } public Collection remove(Object key) { return internalMap.remove(key); } public boolean isEmpty() { return internalMap.isEmpty(); } public boolean containsKey(Object key) { return internalMap.containsKey(key); } public void putAll(Map map) { for (K key : map.keySet()) { put(key, map.get(key)); } } public void putAll(MultiMap map) { for (Iterator it = map.entrySet().iterator(); it.hasNext();) { Map.Entry> entry = (Map.Entry>) it.next(); for (V v : entry.getValue()) { put(entry.getKey(), v); } } } public Set keySet() { return internalMap.keySet(); } public Set>> entrySet() { return internalMap.entrySet(); } public Map> map() { return internalMap; } /** * Gets a collection containing all the values in the map. *

          * This returns a collection containing the combination of values from all keys. * * @return a collection view of the values contained in this map */ public Collection values() { Collection vs = values; return vs != null ? vs : (values = new Values()); } //----------------------------------------------------------------------- /** * Inner class to view the elements. */ private class Values extends AbstractCollection { public Iterator iterator() { return new ValueIterator(); } public int size() { int compt = 0; Iterator it = iterator(); while (it.hasNext()) { it.next(); compt++; } return compt; } public void clear() { MultiHashMap.this.clear(); } } /** * Inner iterator to view the elements. */ private class ValueIterator implements Iterator { private Iterator> backedIterator; private Iterator tempIterator; private ValueIterator() { backedIterator = internalMap.values().iterator(); } private boolean searchNextIterator() { while (tempIterator == null || tempIterator.hasNext() == false) { if (backedIterator.hasNext() == false) { return false; } tempIterator = backedIterator.next().iterator(); } return true; } public boolean hasNext() { return searchNextIterator(); } public V next() { if (searchNextIterator() == false) { throw new NoSuchElementException(); } return tempIterator.next(); } public void remove() { if (tempIterator == null) { throw new IllegalStateException(); } tempIterator.remove(); } } //----------------------------------------------------------------------- /** * Clones the map creating an independent copy. *

          * The clone will shallow clone the collections15 as well as the map. * * @return the cloned map */ public Object clone() { MultiHashMap cloned = new MultiHashMap(); for (Iterator>> it = internalMap.entrySet().iterator(); it.hasNext();) { Map.Entry> entry = it.next(); for (V v : entry.getValue()) { cloned.put(entry.getKey(), v); } } return cloned; } public boolean equals(Object obj) { if (obj instanceof MultiHashMap) { return internalMap.equals(((MultiHashMap)obj).map()); } else return false; } public int hashCode() { return internalMap.hashCode(); } /** * Creates a new instance of the map value Collection container. *

          * This method can be overridden to use your own collection type. * * @param coll the collection to copy, may be null * @return the new collection */ protected Collection createCollection(Collection coll) { if (coll == null) { return new ArrayList(); } else { return new ArrayList(coll); } } public String toString() { return internalMap.toString(); } } collections-generic-4.01/src/java/org/apache/commons/collections15/ClosureUtils.java0000644000175000017500000003336610464140763030773 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2002-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15; import org.apache.commons.collections15.functors.*; import java.util.Collection; import java.util.Iterator; import java.util.Map; /** * ClosureUtils provides reference implementations and utilities * for the Closure functor interface. The supplied closures are: *

            *
          • Invoker - invokes a method on the input object *
          • For - repeatedly calls a closure for a fixed number of times *
          • While - repeatedly calls a closure while a predicate is true *
          • DoWhile - repeatedly calls a closure while a predicate is true *
          • Chained - chains two or more closures together *
          • Switch - calls one closure based on one or more predicates *
          • SwitchMap - calls one closure looked up from a Map *
          • Transformer - wraps a Transformer as a Closure *
          • NOP - does nothing *
          • Exception - always throws an exception *
          * All the supplied closures are Serializable. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:19 $ * @since Commons Collections 3.0 */ public class ClosureUtils { /** * This class is not normally instantiated. */ public ClosureUtils() { super(); } /** * Gets a Closure that always throws an exception. * This could be useful during testing as a placeholder. * * @return the closure * @see org.apache.commons.collections15.functors.ExceptionClosure */ public static Closure exceptionClosure() { return ExceptionClosure.INSTANCE; } /** * Gets a Closure that will do nothing. * This could be useful during testing as a placeholder. * * @return the closure * @see org.apache.commons.collections15.functors.NOPClosure */ public static Closure nopClosure() { return NOPClosure.INSTANCE; } /** * Creates a Closure that calls a Transformer each time it is called. * The transformer will be called using the closure's input object. * The transformer's result will be ignored. * * @param transformer the transformer to run each time in the closure, null means nop * @return the closure * @see org.apache.commons.collections15.functors.TransformerClosure */ public static Closure asClosure(Transformer transformer) { return TransformerClosure.getInstance(transformer); } /** * Creates a Closure that will call the closure count times. *

          * A null closure or zero count returns the NOPClosure. * * @param count the number of times to loop * @param closure the closure to call repeatedly * @return the for closure * @see org.apache.commons.collections15.functors.ForClosure */ public static Closure forClosure(int count, Closure closure) { return ForClosure.getInstance(count, closure); } /** * Creates a Closure that will call the closure repeatedly until the * predicate returns false. * * @param predicate the predicate to use as an end of loop test, not null * @param closure the closure to call repeatedly, not null * @return the while closure * @throws IllegalArgumentException if either argument is null * @see org.apache.commons.collections15.functors.WhileClosure */ public static Closure whileClosure(Predicate predicate, Closure closure) { return WhileClosure.getInstance(predicate, closure, false); } /** * Creates a Closure that will call the closure once and then repeatedly * until the predicate returns false. * * @param closure the closure to call repeatedly, not null * @param predicate the predicate to use as an end of loop test, not null * @return the do-while closure * @throws IllegalArgumentException if either argument is null * @see org.apache.commons.collections15.functors.WhileClosure */ public static Closure doWhileClosure(Closure closure, Predicate predicate) { return WhileClosure.getInstance(predicate, closure, true); } /** * Creates a Closure that will invoke a specific method on the closure's * input object by reflection. * * @param methodName the name of the method * @return the invoker closure * @throws IllegalArgumentException if the method name is null * @see org.apache.commons.collections15.functors.InvokerTransformer * @see org.apache.commons.collections15.functors.TransformerClosure */ public static Closure invokerClosure(String methodName) { // reuse transformer as it has caching - this is lazy really, should have inner class here return asClosure(InvokerTransformer.getInstance(methodName)); } /** * Creates a Closure that will invoke a specific method on the closure's * input object by reflection. * * @param methodName the name of the method * @param paramTypes the parameter types * @param args the arguments * @return the invoker closure * @throws IllegalArgumentException if the method name is null * @throws IllegalArgumentException if the paramTypes and args don't match * @see org.apache.commons.collections15.functors.InvokerTransformer * @see org.apache.commons.collections15.functors.TransformerClosure */ public static Closure invokerClosure(String methodName, Class[] paramTypes, Object[] args) { // reuse transformer as it has caching - this is lazy really, should have inner class here return asClosure(InvokerTransformer.getInstance(methodName, paramTypes, args)); } /** * Create a new Closure that calls two Closures, passing the result of * the first into the second. * * @param closure1 the first closure * @param closure2 the second closure * @return the chained closure * @throws IllegalArgumentException if either closure is null * @see org.apache.commons.collections15.functors.ChainedClosure */ public static Closure chainedClosure(Closure closure1, Closure closure2) { return ChainedClosure.getInstance(closure1, closure2); } /** * Create a new Closure that calls each closure in turn, passing the * result into the next closure. * * @param closures an array of closures to chain * @return the chained closure * @throws IllegalArgumentException if the closures array is null * @throws IllegalArgumentException if any closure in the array is null * @see org.apache.commons.collections15.functors.ChainedClosure */ public static Closure chainedClosure(Closure[] closures) { return ChainedClosure.getInstance(closures); } /** * Create a new Closure that calls each closure in turn, passing the * result into the next closure. The ordering is that of the iterator() * method on the collection. * * @param closures a collection of closures to chain * @return the chained closure * @throws IllegalArgumentException if the closures collection is null * @throws IllegalArgumentException if the closures collection is empty * @throws IllegalArgumentException if any closure in the collection is null * @see org.apache.commons.collections15.functors.ChainedClosure */ public static Closure chainedClosure(Collection closures) { return ChainedClosure.getInstance(closures); } /** * Create a new Closure that calls one of two closures depending * on the specified predicate. * * @param predicate the predicate to switch on * @param trueClosure the closure called if the predicate is true * @param falseClosure the closure called if the predicate is false * @return the switch closure * @throws IllegalArgumentException if the predicate is null * @throws IllegalArgumentException if either closure is null * @see org.apache.commons.collections15.functors.IfClosure */ public static Closure ifClosure(Predicate predicate, Closure trueClosure, Closure falseClosure) { return IfClosure.getInstance(predicate, trueClosure, falseClosure); } /** * Create a new Closure that calls one of the closures depending * on the predicates. *

          * The closure at array location 0 is called if the predicate at array * location 0 returned true. Each predicate is evaluated * until one returns true. * * @param predicates an array of predicates to check, not null * @param closures an array of closures to call, not null * @return the switch closure * @throws IllegalArgumentException if the either array is null * @throws IllegalArgumentException if any element in the arrays is null * @throws IllegalArgumentException if the arrays are different sizes * @see org.apache.commons.collections15.functors.SwitchClosure */ public static Closure switchClosure(Predicate[] predicates, Closure[] closures) { return SwitchClosure.getInstance(predicates, closures, null); } /** * Create a new Closure that calls one of the closures depending * on the predicates. *

          * The closure at array location 0 is called if the predicate at array * location 0 returned true. Each predicate is evaluated * until one returns true. If no predicates evaluate to true, the default * closure is called. * * @param predicates an array of predicates to check, not null * @param closures an array of closures to call, not null * @param defaultClosure the default to call if no predicate matches * @return the switch closure * @throws IllegalArgumentException if the either array is null * @throws IllegalArgumentException if any element in the arrays is null * @throws IllegalArgumentException if the arrays are different sizes * @see org.apache.commons.collections15.functors.SwitchClosure */ public static Closure switchClosure(Predicate[] predicates, Closure[] closures, Closure defaultClosure) { return SwitchClosure.getInstance(predicates, closures, defaultClosure); } /** * Create a new Closure that calls one of the closures depending * on the predicates. *

          * The Map consists of Predicate keys and Closure values. A closure * is called if its matching predicate returns true. Each predicate is evaluated * until one returns true. If no predicates evaluate to true, the default * closure is called. The default closure is set in the map with a * null key. The ordering is that of the iterator() method on the entryset * collection of the map. * * @param predicatesAndClosures a map of predicates to closures * @return the switch closure * @throws IllegalArgumentException if the map is null * @throws IllegalArgumentException if the map is empty * @throws IllegalArgumentException if any closure in the map is null * @throws ClassCastException if the map elements are of the wrong type * @see org.apache.commons.collections15.functors.SwitchClosure */ public static Closure switchClosure(Map, Closure> predicatesAndClosures) { return SwitchClosure.getInstance(predicatesAndClosures); } /** * Create a new Closure that uses the input object as a key to find the * closure to call. *

          * The Map consists of object keys and Closure values. A closure * is called if the input object equals the key. If there is no match, the * default closure is called. The default closure is set in the map * using a null key. * * @param objectsAndClosures a map of objects to closures * @return the closure * @throws IllegalArgumentException if the map is null * @throws IllegalArgumentException if the map is empty * @throws IllegalArgumentException if any closure in the map is null * @see org.apache.commons.collections15.functors.SwitchClosure */ public static Closure switchMapClosure(Map> objectsAndClosures) { Closure[] trs = null; Predicate[] preds = null; if (objectsAndClosures == null) { throw new IllegalArgumentException("The object and closure map must not be null"); } Closure def = (Closure) objectsAndClosures.remove(null); int size = objectsAndClosures.size(); trs = new Closure[size]; preds = new Predicate[size]; int i = 0; for (Iterator it = objectsAndClosures.entrySet().iterator(); it.hasNext();) { Map.Entry entry = (Map.Entry) it.next(); preds[i] = EqualPredicate.getInstance(entry.getKey()); trs[i] = (Closure) entry.getValue(); i++; } return switchClosure(preds, trs, def); } } collections-generic-4.01/src/java/org/apache/commons/collections15/BeanMap.java0000644000175000017500000006332610464140763027640 0ustar giovannigiovanni// GenericsNote: Converted to . /* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15; import org.apache.commons.collections15.keyvalue.AbstractMapEntry; import org.apache.commons.collections15.list.UnmodifiableList; import org.apache.commons.collections15.set.UnmodifiableSet; import java.beans.BeanInfo; import java.beans.IntrospectionException; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.*; /** * An implementation of Map for JavaBeans which uses introspection to * get and put properties in the bean. *

          * If an exception occurs during attempts to get or set a property then the * property is considered non existent in the Map *

          * * @author James Strachan * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:19 $ * @since Commons Collections 1.0 */ public class BeanMap extends AbstractMap implements Cloneable { private transient Object bean; private transient HashMap readMethods = new HashMap(); private transient HashMap writeMethods = new HashMap(); private transient HashMap types = new HashMap(); /** * An empty array. Used to invoke accessors via reflection. */ public static final Object[] NULL_ARGUMENTS = {}; /** * Maps primitive Class types to transformers. The transformer * transform strings into the appropriate primitive wrapper. */ public static HashMap defaultTransformers = new HashMap(); static { defaultTransformers.put(Boolean.TYPE, new Transformer() { public Object transform(Object input) { return Boolean.valueOf(input.toString()); } }); defaultTransformers.put(Character.TYPE, new Transformer() { public Object transform(Object input) { return new Character(input.toString().charAt(0)); } }); defaultTransformers.put(Byte.TYPE, new Transformer() { public Object transform(Object input) { return Byte.valueOf(input.toString()); } }); defaultTransformers.put(Short.TYPE, new Transformer() { public Object transform(Object input) { return Short.valueOf(input.toString()); } }); defaultTransformers.put(Integer.TYPE, new Transformer() { public Object transform(Object input) { return Integer.valueOf(input.toString()); } }); defaultTransformers.put(Long.TYPE, new Transformer() { public Object transform(Object input) { return Long.valueOf(input.toString()); } }); defaultTransformers.put(Float.TYPE, new Transformer() { public Object transform(Object input) { return Float.valueOf(input.toString()); } }); defaultTransformers.put(Double.TYPE, new Transformer() { public Object transform(Object input) { return Double.valueOf(input.toString()); } }); } // Constructors //------------------------------------------------------------------------- /** * Constructs a new empty BeanMap. */ public BeanMap() { } /** * Constructs a new BeanMap that operates on the * specified bean. If the given bean is null, then * this map will be empty. * * @param bean the bean for this map to operate on */ public BeanMap(Object bean) { this.bean = bean; initialise(); } // Map interface //------------------------------------------------------------------------- public String toString() { return "BeanMap<" + String.valueOf(bean) + ">"; } /** * Clone this bean map using the following process: *

          *

            *
          • If there is no underlying bean, return a cloned BeanMap without a * bean. *

            *

          • Since there is an underlying bean, try to instantiate a new bean of * the same type using Class.newInstance(). *

            *

          • If the instantiation fails, throw a CloneNotSupportedException *

            *

          • Clone the bean map and set the newly instantiated bean as the * underlying bean for the bean map. *

            *

          • Copy each property that is both readable and writable from the * existing object to a cloned bean map. *

            *

          • If anything fails along the way, throw a * CloneNotSupportedException. *

            *

              */ public Object clone() throws CloneNotSupportedException { BeanMap newMap = (BeanMap) super.clone(); if (bean == null) { // no bean, just an empty bean map at the moment. return a newly // cloned and empty bean map. return newMap; } Object newBean = null; Class beanClass = null; try { beanClass = bean.getClass(); newBean = beanClass.newInstance(); } catch (Exception e) { // unable to instantiate throw new CloneNotSupportedException("Unable to instantiate the underlying bean \"" + beanClass.getName() + "\": " + e); } try { newMap.setBean(newBean); } catch (Exception exception) { throw new CloneNotSupportedException("Unable to set bean in the cloned bean map: " + exception); } try { // copy only properties that are readable and writable. If its // not readable, we can't get the value from the old map. If // its not writable, we can't write a value into the new map. Iterator readableKeys = readMethods.keySet().iterator(); while (readableKeys.hasNext()) { String key = readableKeys.next(); if (getWriteMethod(key) != null) { newMap.put(key, get(key)); } } } catch (Exception exception) { throw new CloneNotSupportedException("Unable to copy bean values to cloned bean map: " + exception); } return newMap; } /** * Puts all of the writable properties from the given BeanMap into this * BeanMap. Read-only and Write-only properties will be ignored. * * @param map the BeanMap whose properties to put */ public void putAllWriteable(BeanMap map) { Iterator readableKeys = map.readMethods.keySet().iterator(); while (readableKeys.hasNext()) { String key = readableKeys.next(); if (getWriteMethod(key) != null) { this.put(key, map.get(key)); } } } /** * This method reinitializes the bean map to have default values for the * bean's properties. This is accomplished by constructing a new instance * of the bean which the map uses as its underlying data source. This * behavior for clear() differs from the Map contract in that * the mappings are not actually removed from the map (the mappings for a * BeanMap are fixed). */ public void clear() { if (bean == null) return; Class beanClass = null; try { beanClass = bean.getClass(); bean = beanClass.newInstance(); } catch (Exception e) { throw new UnsupportedOperationException("Could not create new instance of class: " + beanClass); } } /** * Returns true if the bean defines a property with the given name. *

              * The given name must be a String; if not, this method * returns false. This method will also return false if the bean * does not define a property with that name. *

              * Write-only properties will not be matched as the test operates against * property read methods. * * @param name the name of the property to check * @return false if the given name is null or is not a String; * false if the bean does not define a property with that name; or * true if the bean does define a property with that name */ public boolean containsKey(String name) { Method method = getReadMethod(name); return method != null; } /** * Returns true if the bean defines a property whose current value is * the given object. * * @param value the value to check * @return false true if the bean has at least one property whose * current value is that object, false otherwise */ public boolean containsValue(Object value) { // use default implementation return super.containsValue(value); } /** * Returns the value of the bean's property with the given name. *

              * The given name must be a {@link String} and must not be * null; otherwise, this method returns null. * If the bean defines a property with the given name, the value of * that property is returned. Otherwise, null is * returned. *

              * Write-only properties will not be matched as the test operates against * property read methods. * * @param name the name of the property whose value to return * @return the value of the property with that name */ public Object get(String name) { if (bean != null) { Method method = getReadMethod(name); if (method != null) { try { return method.invoke(bean, NULL_ARGUMENTS); } catch (IllegalAccessException e) { logWarn(e); } catch (IllegalArgumentException e) { logWarn(e); } catch (InvocationTargetException e) { logWarn(e); } catch (NullPointerException e) { logWarn(e); } } } return null; } /** * Sets the bean property with the given name to the given value. * * @param name the name of the property to set * @param value the value to set that property to * @return the previous value of that property * @throws IllegalArgumentException if the given name is null; * if the given name is not a {@link String}; if the bean doesn't * define a property with that name; or if the bean property with * that name is read-only */ public Object put(String name, Object value) throws IllegalArgumentException, ClassCastException { if (bean != null) { Object oldValue = get(name); Method method = getWriteMethod(name); if (method == null) { throw new IllegalArgumentException("The bean of type: " + bean.getClass().getName() + " has no property called: " + name); } try { Object[] arguments = createWriteMethodArguments(method, value); method.invoke(bean, arguments); Object newValue = get(name); firePropertyChange(name, oldValue, newValue); } catch (InvocationTargetException e) { logInfo(e); throw new IllegalArgumentException(e.getMessage()); } catch (IllegalAccessException e) { logInfo(e); throw new IllegalArgumentException(e.getMessage()); } return oldValue; } return null; } /** * Returns the number of properties defined by the bean. * * @return the number of properties defined by the bean */ public int size() { return readMethods.size(); } /** * Get the keys for this BeanMap. *

              * Write-only properties are not included in the returned set of * property names, although it is possible to set their value and to get * their type. * * @return BeanMap keys. The Set returned by this method is not * modifiable. */ public Set keySet() { return UnmodifiableSet.decorate(readMethods.keySet()); } /** * Gets a Set of MapEntry objects that are the mappings for this BeanMap. *

              * Each MapEntry can be set but not removed. * * @return the unmodifiable set of mappings */ public Set> entrySet() { return UnmodifiableSet.decorate(new AbstractSet>() { public Iterator> iterator() { return entryIterator(); } public int size() { return BeanMap.this.readMethods.size(); } }); } /** * Returns the values for the BeanMap. * * @return values for the BeanMap. The returned collection is not * modifiable. */ public Collection values() { ArrayList answer = new ArrayList(readMethods.size()); for (Iterator iter = valueIterator(); iter.hasNext();) { answer.add(iter.next()); } return UnmodifiableList.decorate(answer); } // Helper methods //------------------------------------------------------------------------- /** * Returns the type of the property with the given name. * * @param name the name of the property * @return the type of the property, or null if no such * property exists */ public Class getType(String name) { return (Class) types.get(name); } /** * Convenience method for getting an iterator over the keys. *

              * Write-only properties will not be returned in the iterator. * * @return an iterator over the keys */ public Iterator keyIterator() { return readMethods.keySet().iterator(); } /** * Convenience method for getting an iterator over the values. * * @return an iterator over the values */ public Iterator valueIterator() { final Iterator iter = keyIterator(); return new Iterator() { public boolean hasNext() { return iter.hasNext(); } public Object next() { Object key = iter.next(); return get(key); } public void remove() { throw new UnsupportedOperationException("remove() not supported for BeanMap"); } }; } /** * Convenience method for getting an iterator over the entries. * * @return an iterator over the entries */ public Iterator> entryIterator() { final Iterator iter = keyIterator(); return new Iterator>() { public boolean hasNext() { return iter.hasNext(); } public Entry next() { String key = iter.next(); Object value = get(key); return new MyMapEntry(BeanMap.this, key, value); } public void remove() { throw new UnsupportedOperationException("remove() not supported for BeanMap"); } }; } // Properties //------------------------------------------------------------------------- /** * Returns the bean currently being operated on. The return value may * be null if this map is empty. * * @return the bean being operated on by this map */ public Object getBean() { return bean; } /** * Sets the bean to be operated on by this map. The given value may * be null, in which case this map will be empty. * * @param newBean the new bean to operate on */ public void setBean(Object newBean) { bean = newBean; reinitialise(); } /** * Returns the accessor for the property with the given name. * * @param name the name of the property * @return the accessor method for the property, or null */ public Method getReadMethod(String name) { return readMethods.get(name); } /** * Returns the mutator for the property with the given name. * * @param name the name of the property * @return the mutator method for the property, or null */ public Method getWriteMethod(String name) { return (Method) writeMethods.get(name); } // Implementation methods //------------------------------------------------------------------------- /** * Reinitializes this bean. Called during {@link #setBean(Object)}. * Does introspection to find properties. */ protected void reinitialise() { readMethods.clear(); writeMethods.clear(); types.clear(); initialise(); } private void initialise() { if (getBean() == null) return; Class beanClass = getBean().getClass(); try { //BeanInfo beanInfo = Introspector.getBeanInfo( bean, null ); BeanInfo beanInfo = Introspector.getBeanInfo(beanClass); PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); if (propertyDescriptors != null) { for (int i = 0; i < propertyDescriptors.length; i++) { PropertyDescriptor propertyDescriptor = propertyDescriptors[i]; if (propertyDescriptor != null) { String name = propertyDescriptor.getName(); Method readMethod = propertyDescriptor.getReadMethod(); Method writeMethod = propertyDescriptor.getWriteMethod(); Class aType = propertyDescriptor.getPropertyType(); if (readMethod != null) { readMethods.put(name, readMethod); } if (writeMethods != null) { writeMethods.put(name, writeMethod); } types.put(name, aType); } } } } catch (IntrospectionException e) { logWarn(e); } } /** * Called during a successful {@link #put(Object,Object)} operation. * Default implementation does nothing. Override to be notified of * property changes in the bean caused by this map. * * @param key the name of the property that changed * @param oldValue the old value for that property * @param newValue the new value for that property */ protected void firePropertyChange(String key, Object oldValue, Object newValue) { } // Implementation classes //------------------------------------------------------------------------- /** * Map entry used by {@link BeanMap}. */ protected static class MyMapEntry extends AbstractMapEntry { private BeanMap owner; /** * Constructs a new MyMapEntry. * * @param owner the BeanMap this entry belongs to * @param key the key for this entry * @param value the value for this entry */ protected MyMapEntry(BeanMap owner, String key, Object value) { super(key, value); this.owner = owner; } /** * Sets the value. * * @param value the new value for the entry * @return the old value for the entry */ public Object setValue(Object value) { String key = getKey(); Object oldValue = owner.get(key); owner.put(key, value); Object newValue = owner.get(key); super.setValue(newValue); return oldValue; } } /** * Creates an array of parameters to pass to the given mutator method. * If the given object is not the right type to pass to the method * directly, it will be converted using {@link #convertType(Class,Object)}. * * @param method the mutator method * @param value the value to pass to the mutator method * @return an array containing one object that is either the given value * or a transformed value * @throws IllegalAccessException if {@link #convertType(Class,Object)} * raises it * @throws IllegalArgumentException if any other exception is raised * by {@link #convertType(Class,Object)} */ protected Object[] createWriteMethodArguments(Method method, Object value) throws IllegalAccessException, ClassCastException { try { if (value != null) { Class[] types = method.getParameterTypes(); if (types != null && types.length > 0) { Class paramType = types[0]; if (!paramType.isAssignableFrom(value.getClass())) { value = convertType(paramType, value); } } } Object[] answer = {value}; return answer; } catch (InvocationTargetException e) { logInfo(e); throw new IllegalArgumentException(e.getMessage()); } catch (InstantiationException e) { logInfo(e); throw new IllegalArgumentException(e.getMessage()); } } /** * Converts the given value to the given type. First, reflection is * is used to find a public constructor declared by the given class * that takes one argument, which must be the precise type of the * given value. If such a constructor is found, a new object is * created by passing the given value to that constructor, and the * newly constructed object is returned.

              *

              * If no such constructor exists, and the given type is a primitive * type, then the given value is converted to a string using its * {@link Object#toString() toString()} method, and that string is * parsed into the correct primitive type using, for instance, * {@link Integer#valueOf(String)} to convert the string into an * int.

              *

              * If no special constructor exists and the given type is not a * primitive type, this method returns the original value. * * @param newType the type to convert the value to * @param value the value to convert * @return the converted value * @throws NumberFormatException if newType is a primitive type, and * the string representation of the given value cannot be converted * to that type * @throws InstantiationException if the constructor found with * reflection raises it * @throws InvocationTargetException if the constructor found with * reflection raises it * @throws IllegalAccessException never * @throws IllegalArgumentException never */ protected Object convertType(Class newType, Object value) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { // try call constructor Class[] types = {value.getClass()}; try { Constructor constructor = newType.getConstructor(types); Object[] arguments = {value}; return constructor.newInstance(arguments); } catch (NoSuchMethodException e) { // try using the transformers Transformer transformer = getTypeTransformer(newType); if (transformer != null) { return transformer.transform(value); } return value; } } /** * Returns a transformer for the given primitive type. * * @param aType the primitive type whose transformer to return * @return a transformer that will convert strings into that type, * or null if the given type is not a primitive type */ protected Transformer getTypeTransformer(Class aType) { return (Transformer) defaultTransformers.get(aType); } /** * Logs the given exception to System.out. Used to display * warnings while accessing/mutating the bean. * * @param ex the exception to log */ protected void logInfo(Exception ex) { // Deliberately do not use LOG4J or Commons Logging to avoid dependencies System.out.println("INFO: Exception: " + ex); } /** * Logs the given exception to System.err. Used to display * errors while accessing/mutating the bean. * * @param ex the exception to log */ protected void logWarn(Exception ex) { // Deliberately do not use LOG4J or Commons Logging to avoid dependencies System.out.println("WARN: Exception: " + ex); ex.printStackTrace(); } } collections-generic-4.01/src/java/org/apache/commons/collections15/SetUtils.java0000644000175000017500000002722010464140760030077 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2002-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15; import org.apache.commons.collections15.set.*; import java.util.*; /** * Provides utility methods and decorators for * {@link Set} and {@link SortedSet} instances. * * @author Paul Jack * @author Stephen Colebourne * @author Neil O'Toole * @author Matt Hall, John Watkinson, Matthew Hawthorne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:19 $ * @since Commons Collections 2.1 */ public class SetUtils { /** * An empty unmodifiable set. * This uses the {@link Collections} implementation * and is provided for completeness. */ public static final Set EMPTY_SET = Collections.EMPTY_SET; /** * An empty unmodifiable sorted set. * This is not provided in the JDK. */ public static final SortedSet EMPTY_SORTED_SET = UnmodifiableSortedSet.decorate(new TreeSet()); /** * SetUtils should not normally be instantiated. */ public SetUtils() { } //----------------------------------------------------------------------- /** * Tests two sets for equality as per the equals() contract * in {@link java.util.Set#equals(java.lang.Object)}. *

              * This method is useful for implementing Set when you cannot * extend AbstractSet. The method takes Collection instances to enable other * collection types to use the Set implementation algorithm. *

              * The relevant text (slightly paraphrased as this is a static method) is: *

              *

              Two sets are considered equal if they have * the same size, and every member of the first set is contained in * the second. This ensures that the equals method works * properly across different implementations of the Set * interface.

              *

              *

              * This implementation first checks if the two sets are the same object: * if so it returns true. Then, it checks if the two sets are * identical in size; if not, it returns false. If so, it returns * a.containsAll((Collection) b).

              *
              * * @param set1 the first set, may be null * @param set2 the second set, may be null * @return whether the sets are equal by value comparison * @see java.util.Set */ public static boolean isEqualSet(final Collection set1, final Collection set2) { if (set1 == set2) { return true; } if (set1 == null || set2 == null || set1.size() != set2.size()) { return false; } return set1.containsAll(set2); } /** * Generates a hash code using the algorithm specified in * {@link java.util.Set#hashCode()}. *

              * This method is useful for implementing Set when you cannot * extend AbstractSet. The method takes Collection instances to enable other * collection types to use the Set implementation algorithm. * * @param set the set to calculate the hash code for, may be null * @return the hash code * @see java.util.Set#hashCode() */ public static int hashCodeForSet(final Collection set) { if (set == null) { return 0; } int hashCode = 0; Iterator it = set.iterator(); Object obj = null; while (it.hasNext()) { obj = it.next(); if (obj != null) { hashCode += obj.hashCode(); } } return hashCode; } //----------------------------------------------------------------------- /** * Returns a synchronized set backed by the given set. *

              * You must manually synchronize on the returned buffer's iterator to * avoid non-deterministic behavior: *

              *

                   * Set s = SetUtils.synchronizedSet(mySet);
                   * synchronized (s) {
                   *     Iterator i = s.iterator();
                   *     while (i.hasNext()) {
                   *         process (i.next());
                   *     }
                   * }
                   * 
              *

              * This method uses the implementation in the decorators subpackage. * * @param set the set to synchronize, must not be null * @return a synchronized set backed by the given set * @throws IllegalArgumentException if the set is null */ public static Set synchronizedSet(Set set) { return SynchronizedSet.decorate(set); } /** * Returns an unmodifiable set backed by the given set. *

              * This method uses the implementation in the decorators subpackage. * * @param set the set to make unmodifiable, must not be null * @return an unmodifiable set backed by the given set * @throws IllegalArgumentException if the set is null */ public static Set unmodifiableSet(Set set) { return UnmodifiableSet.decorate(set); } /** * Returns a predicated (validating) set backed by the given set. *

              * Only objects that pass the test in the given predicate can be added to the set. * Trying to add an invalid object results in an IllegalArgumentException. * It is important not to use the original set after invoking this method, * as it is a backdoor for adding invalid objects. * * @param set the set to predicate, must not be null * @param predicate the predicate for the set, must not be null * @return a predicated set backed by the given set * @throws IllegalArgumentException if the Set or Predicate is null */ public static Set predicatedSet(Set set, Predicate predicate) { return PredicatedSet.decorate(set, predicate); } /** * Returns a typed set backed by the given set. *

              * Only objects of the specified type can be added to the set. * * @param set the set to limit to a specific type, must not be null * @param type the type of objects which may be added to the set * @return a typed set backed by the specified set * @deprecated Made obsolete by Java 1.5 generics. */ public static Set typedSet(Set set, Class type) { return TypedSet.decorate(set, type); } /** * Returns a transformed set backed by the given set. *

              * Each object is passed through the transformer as it is added to the * Set. It is important not to use the original set after invoking this * method, as it is a backdoor for adding untransformed objects. * * @param set the set to transform, must not be null * @param transformer the transformer for the set, must not be null * @return a transformed set backed by the given set * @throws IllegalArgumentException if the Set or Transformer is null */ public static Set transformedSet(Set set, Transformer transformer) { return TransformedSet.decorate(set, transformer); } /** * Returns a set that maintains the order of elements that are added * backed by the given set. *

              * If an element is added twice, the order is determined by the first add. * The order is observed through the iterator or toArray. * * @param set the set to order, must not be null * @return an ordered set backed by the given set * @throws IllegalArgumentException if the Set is null */ public static Set orderedSet(Set set) { return ListOrderedSet.decorate(set); } //----------------------------------------------------------------------- /** * Returns a synchronized sorted set backed by the given sorted set. *

              * You must manually synchronize on the returned buffer's iterator to * avoid non-deterministic behavior: *

              *

                   * Set s = SetUtils.synchronizedSet(mySet);
                   * synchronized (s) {
                   *     Iterator i = s.iterator();
                   *     while (i.hasNext()) {
                   *         process (i.next());
                   *     }
                   * }
                   * 
              *

              * This method uses the implementation in the decorators subpackage. * * @param set the sorted set to synchronize, must not be null * @return a synchronized set backed by the given set * @throws IllegalArgumentException if the set is null */ public static SortedSet synchronizedSortedSet(SortedSet set) { return SynchronizedSortedSet.decorate(set); } /** * Returns an unmodifiable sorted set backed by the given sorted set. *

              * This method uses the implementation in the decorators subpackage. * * @param set the sorted set to make unmodifiable, must not be null * @return an unmodifiable set backed by the given set * @throws IllegalArgumentException if the set is null */ public static SortedSet unmodifiableSortedSet(SortedSet set) { return UnmodifiableSortedSet.decorate(set); } /** * Returns a predicated (validating) sorted set backed by the given sorted set. *

              * Only objects that pass the test in the given predicate can be added to the set. * Trying to add an invalid object results in an IllegalArgumentException. * It is important not to use the original set after invoking this method, * as it is a backdoor for adding invalid objects. * * @param set the sorted set to predicate, must not be null * @param predicate the predicate for the sorted set, must not be null * @return a predicated sorted set backed by the given sorted set * @throws IllegalArgumentException if the Set or Predicate is null */ public static SortedSet predicatedSortedSet(SortedSet set, Predicate predicate) { return PredicatedSortedSet.decorate(set, predicate); } /** * Returns a typed sorted set backed by the given set. *

              * Only objects of the specified type can be added to the set. * * @param set the set to limit to a specific type, must not be null * @param type the type of objects which may be added to the set * @return a typed set backed by the specified set * @deprecated made obsolete by Java 1.5 generics. */ public static SortedSet typedSortedSet(SortedSet set, Class type) { return TypedSortedSet.decorate(set, type); } /** * Returns a transformed sorted set backed by the given set. *

              * Each object is passed through the transformer as it is added to the * Set. It is important not to use the original set after invoking this * method, as it is a backdoor for adding untransformed objects. * * @param set the set to transform, must not be null * @param transformer the transformer for the set, must not be null * @return a transformed set backed by the given set * @throws IllegalArgumentException if the Set or Transformer is null */ public static SortedSet transformedSortedSet(SortedSet set, Transformer transformer) { return TransformedSortedSet.decorate(set, transformer); } } collections-generic-4.01/src/java/org/apache/commons/collections15/Transformer.java0000644000175000017500000000363210464140760030626 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15; /** * Defines a functor interface implemented by classes that transform one * object into another. *

              * A Transformer converts the input object to the output object. * The input object should be left unchanged. * Transformers are typically used for type conversions, or extracting data * from an object. *

              * Standard implementations of common transformers are provided by * {@link TransformerUtils}. These include method invokation, returning a constant, * cloning and returning the string value. * * @author James Strachan * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:19 $ * @since Commons Collections 1.0 */ public interface Transformer { /** * Transforms the input object (leaving it unchanged) into some output object. * * @param input the object to be transformed, should be left unchanged * @return a transformed object * @throws ClassCastException (runtime) if the input is the wrong class * @throws IllegalArgumentException (runtime) if the input is invalid * @throws FunctorException (runtime) if the transform cannot be completed */ public O transform(I input); } collections-generic-4.01/src/java/org/apache/commons/collections15/package.html0000644000175000017500000000233010464140762027736 0ustar giovannigiovanni

              This package contains the interfaces and utilities shared across all the subpackages of this component.

              The following collection implementations are provided in the package:

              • ArrayStack - a non synchronized Stack that follows the same API as java util Stack
              • BeanMap - a map that wraps a JavaBean, representing its properties as map keys and values
              • ExtendedProperties - extends the Properties class to add extra functionality
              • MultiHashMap - an map that stores multiple values against each key

              collections-generic-4.01/src/java/org/apache/commons/collections15/FunctorException.java0000644000175000017500000001007510464140761031623 0ustar giovannigiovanni// GenericsNote: No conversion needed. /* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15; import java.io.PrintStream; import java.io.PrintWriter; /** * Runtime exception thrown from functors. * If required, a root cause error can be wrapped within this one. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:19 $ * @since Commons Collections 3.0 */ public class FunctorException extends RuntimeException { /** * Does JDK support nested exceptions */ private static final boolean JDK_SUPPORTS_NESTED; static { boolean flag = false; try { Throwable.class.getDeclaredMethod("getCause", new Class[0]); flag = true; } catch (NoSuchMethodException ex) { flag = false; } JDK_SUPPORTS_NESTED = flag; } /** * Root cause of the exception */ private final Throwable rootCause; /** * Constructs a new FunctorException without specified * detail message. */ public FunctorException() { super(); this.rootCause = null; } /** * Constructs a new FunctorException with specified * detail message. * * @param msg the error message. */ public FunctorException(String msg) { super(msg); this.rootCause = null; } /** * Constructs a new FunctorException with specified * nested Throwable root cause. * * @param rootCause the exception or error that caused this exception * to be thrown. */ public FunctorException(Throwable rootCause) { super((rootCause == null ? null : rootCause.getMessage())); this.rootCause = rootCause; } /** * Constructs a new FunctorException with specified * detail message and nested Throwable root cause. * * @param msg the error message. * @param rootCause the exception or error that caused this exception * to be thrown. */ public FunctorException(String msg, Throwable rootCause) { super(msg); this.rootCause = rootCause; } /** * Gets the cause of this throwable. * * @return the cause of this throwable, or null */ public Throwable getCause() { return rootCause; } /** * Prints the stack trace of this exception to the standard error stream. */ public void printStackTrace() { printStackTrace(System.err); } /** * Prints the stack trace of this exception to the specified stream. * * @param out the PrintStream to use for output */ public void printStackTrace(PrintStream out) { synchronized (out) { PrintWriter pw = new PrintWriter(out, false); printStackTrace(pw); // Flush the PrintWriter before it's GC'ed. pw.flush(); } } /** * Prints the stack trace of this exception to the specified writer. * * @param out the PrintWriter to use for output */ public void printStackTrace(PrintWriter out) { synchronized (out) { super.printStackTrace(out); if (rootCause != null && JDK_SUPPORTS_NESTED == false) { out.print("Caused by: "); rootCause.printStackTrace(out); } } } } collections-generic-4.01/src/java/org/apache/commons/collections15/ResettableListIterator.java0000644000175000017500000000235510464140761032766 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15; import java.util.ListIterator; /** * Defines a list iterator that can be reset back to an initial state. *

              * This interface allows an iterator to be repeatedly reused. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:19 $ * @since Commons Collections 3.0 */ public interface ResettableListIterator extends ListIterator, ResettableIterator { /** * Resets the iterator back to the position at which the iterator * was created. */ public void reset(); } collections-generic-4.01/src/java/org/apache/commons/collections15/TransformerUtils.java0000644000175000017500000004374310464140765031663 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2002-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15; import org.apache.commons.collections15.functors.*; import java.util.Collection; import java.util.Iterator; import java.util.Map; /** * TransformerUtils provides reference implementations and * utilities for the Transformer functor interface. The supplied transformers are: *

                *
              • Invoker - returns the result of a method call on the input object *
              • Clone - returns a clone of the input object *
              • Constant - always returns the same object *
              • Closure - performs a Closure and returns the input object *
              • Predicate - returns the result of the predicate as a Boolean *
              • Factory - returns a new object from a factory *
              • Chained - chains two or more transformers together *
              • Switch - calls one transformer based on one or more predicates *
              • SwitchMap - calls one transformer looked up from a Map *
              • Instantiate - the Class input object is instantiated *
              • Map - returns an object from a supplied Map *
              • Null - always returns null *
              • NOP - returns the input object, which should be immutable *
              • Exception - always throws an exception *
              • StringValue - returns a java.lang.String representation of the input object *
              * All the supplied transformers are Serializable. * * @author Stephen Colebourne * @author Matt Hall, John Watkinson, James Carman * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:19 $ * @since Commons Collections 3.0 */ public class TransformerUtils { /** * This class is not normally instantiated. */ public TransformerUtils() { super(); } /** * Gets a transformer that always throws an exception. * This could be useful during testing as a placeholder. * * @return the transformer * @see org.apache.commons.collections15.functors.ExceptionTransformer */ public static Transformer exceptionTransformer() { return ExceptionTransformer.INSTANCE; } /** * Gets a transformer that always returns null. * * @return the transformer * @see org.apache.commons.collections15.functors.ConstantTransformer */ public static Transformer nullTransformer() { return ConstantTransformer.NULL_INSTANCE; } /** * Gets a transformer that returns the input object. * The input object should be immutable to maintain the * contract of Transformer (although this is not checked). * * @return the transformer * @see org.apache.commons.collections15.functors.NOPTransformer */ public static Transformer nopTransformer() { return NOPTransformer.INSTANCE; } /** * Gets a transformer that returns a clone of the input * object. The input object will be cloned using one of these * techniques (in order): *
                *
              • public clone method *
              • public copy constructor *
              • serialization clone *
                  * * @return the transformer * @see org.apache.commons.collections15.functors.CloneTransformer */ public static Transformer cloneTransformer() { return CloneTransformer.INSTANCE; } /** * Creates a Transformer that will return the same object each time the * transformer is used. * * @param constantToReturn the constant object to return each time in the transformer * @return the transformer. * @see org.apache.commons.collections15.functors.ConstantTransformer */ public static Transformer constantTransformer(T constantToReturn) { return ConstantTransformer.getInstance(constantToReturn); } /** * Creates a Transformer that calls a Closure each time the transformer is used. * The transformer returns the input object. * * @param closure the closure to run each time in the transformer, not null * @return the transformer * @throws IllegalArgumentException if the closure is null * @see org.apache.commons.collections15.functors.ClosureTransformer */ public static Transformer asTransformer(Closure closure) { return ClosureTransformer.getInstance(closure); } /** * Creates a Transformer that calls a Predicate each time the transformer is used. * The transformer will return either Boolean.TRUE or Boolean.FALSE. * * @param predicate the predicate to run each time in the transformer, not null * @return the transformer * @throws IllegalArgumentException if the predicate is null * @see org.apache.commons.collections15.functors.PredicateTransformer */ public static Transformer asTransformer(Predicate predicate) { return PredicateTransformer.getInstance(predicate); } /** * Creates a Transformer that calls a Factory each time the transformer is used. * The transformer will return the value returned by the factory. * * @param factory the factory to run each time in the transformer, not null * @return the transformer * @throws IllegalArgumentException if the factory is null * @see org.apache.commons.collections15.functors.FactoryTransformer */ public static Transformer asTransformer(Factory factory) { return FactoryTransformer.getInstance(factory); } /** * Create a new Transformer that calls two transformers, passing the result of * the first into the second. * * @param transformer1 the first transformer * @param transformer2 the second transformer * @return the transformer * @throws IllegalArgumentException if either transformer is null * @see org.apache.commons.collections15.functors.ChainedTransformer */ public static Transformer chainedTransformer(Transformer transformer1, Transformer transformer2) { return ChainedTransformer.getInstance(transformer1, transformer2); } /** * Create a new Transformer that calls each transformer in turn, passing the * result into the next transformer. *

                  * Note-- no type safety provided by generics. * * @param transformers an array of transformers to chain * @return the transformer * @throws IllegalArgumentException if the transformers array is null * @throws IllegalArgumentException if any transformer in the array is null * @see org.apache.commons.collections15.functors.ChainedTransformer */ public static Transformer chainedTransformer(Transformer[] transformers) { return ChainedTransformer.getInstance(transformers); } /** * Create a new Transformer that calls each transformer in turn, passing the * result into the next transformer. The ordering is that of the iterator() * method on the collection. *

                  * Note-- no type safety provided by generics. * * @param transformers a collection of transformers to chain * @return the transformer * @throws IllegalArgumentException if the transformers collection is null * @throws IllegalArgumentException if any transformer in the collection is null * @see org.apache.commons.collections15.functors.ChainedTransformer */ public static Transformer chainedTransformer(Collection transformers) { return ChainedTransformer.getInstance(transformers); } /** * Create a new Transformer that calls one of two transformers depending * on the specified predicate. * * @param predicate the predicate to switch on * @param trueTransformer the transformer called if the predicate is true * @param falseTransformer the transformer called if the predicate is false * @return the transformer * @throws IllegalArgumentException if the predicate is null * @throws IllegalArgumentException if either transformer is null * @see org.apache.commons.collections15.functors.SwitchTransformer */ public static Transformer switchTransformer(Predicate predicate, Transformer trueTransformer, Transformer falseTransformer) { return SwitchTransformer.getInstance(new Predicate[]{predicate}, new Transformer[]{trueTransformer}, falseTransformer); } /** * Create a new Transformer that calls one of the transformers depending * on the predicates. The transformer at array location 0 is called if the * predicate at array location 0 returned true. Each predicate is evaluated * until one returns true. If no predicates evaluate to true, null is returned. * * @param predicates an array of predicates to check * @param transformers an array of transformers to call * @return the transformer * @throws IllegalArgumentException if the either array is null * @throws IllegalArgumentException if the either array has 0 elements * @throws IllegalArgumentException if any element in the arrays is null * @throws IllegalArgumentException if the arrays are different sizes * @see org.apache.commons.collections15.functors.SwitchTransformer */ public static Transformer switchTransformer(Predicate[] predicates, Transformer[] transformers) { return SwitchTransformer.getInstance(predicates, transformers, null); } /** * Create a new Transformer that calls one of the transformers depending * on the predicates. The transformer at array location 0 is called if the * predicate at array location 0 returned true. Each predicate is evaluated * until one returns true. If no predicates evaluate to true, the default * transformer is called. If the default transformer is null, null is returned. * * @param predicates an array of predicates to check * @param transformers an array of transformers to call * @param defaultTransformer the default to call if no predicate matches, null means return null * @return the transformer * @throws IllegalArgumentException if the either array is null * @throws IllegalArgumentException if the either array has 0 elements * @throws IllegalArgumentException if any element in the arrays is null * @throws IllegalArgumentException if the arrays are different sizes * @see org.apache.commons.collections15.functors.SwitchTransformer */ public static Transformer switchTransformer(Predicate[] predicates, Transformer[] transformers, Transformer defaultTransformer) { return SwitchTransformer.getInstance(predicates, transformers, defaultTransformer); } /** * Create a new Transformer that calls one of the transformers depending * on the predicates. *

                  * The Map consists of Predicate keys and Transformer values. A transformer * is called if its matching predicate returns true. Each predicate is evaluated * until one returns true. If no predicates evaluate to true, the default * transformer is called. The default transformer is set in the map with a * null key. If no default transformer is set, null will be returned in a default * case. The ordering is that of the iterator() method on the entryset collection * of the map. * * @param predicatesAndTransformers a map of predicates to transformers * @return the transformer * @throws IllegalArgumentException if the map is null * @throws IllegalArgumentException if the map is empty * @throws IllegalArgumentException if any transformer in the map is null * @throws ClassCastException if the map elements are of the wrong type * @see org.apache.commons.collections15.functors.SwitchTransformer */ public static Transformer switchTransformer(Map, Transformer> predicatesAndTransformers) { return SwitchTransformer.getInstance(predicatesAndTransformers); } /** * Create a new Transformer that uses the input object as a key to find the * transformer to call. *

                  * The Map consists of object keys and Transformer values. A transformer * is called if the input object equals the key. If there is no match, the * default transformer is called. The default transformer is set in the map * using a null key. If no default is set, null will be returned in a default case. * * @param objectsAndTransformers a map of objects to transformers * @return the transformer * @throws IllegalArgumentException if the map is null * @throws IllegalArgumentException if the map is empty * @throws IllegalArgumentException if any transformer in the map is null * @see org.apache.commons.collections15.functors.SwitchTransformer */ public static Transformer switchMapTransformer(Map> objectsAndTransformers) { Transformer[] trs = null; Predicate[] preds = null; if (objectsAndTransformers == null) { throw new IllegalArgumentException("The object and transformer map must not be null"); } Transformer def = objectsAndTransformers.remove(null); int size = objectsAndTransformers.size(); trs = new Transformer[size]; preds = new Predicate[size]; int i = 0; for (Iterator>> it = objectsAndTransformers.entrySet().iterator(); it.hasNext();) { Map.Entry> entry = it.next(); preds[i] = EqualPredicate.getInstance(entry.getKey()); trs[i] = entry.getValue(); i++; } return switchTransformer(preds, trs, def); } /** * Gets a Transformer that expects an input Class object that it will instantiate. * * @return the transformer * @see org.apache.commons.collections15.functors.InstantiateTransformer */ public static Transformer instantiateTransformer() { return InstantiateTransformer.NO_ARG_INSTANCE; } /** * Creates a Transformer that expects an input Class object that it will * instantiate. The constructor used is determined by the arguments specified * to this method. * * @param paramTypes parameter types for the constructor, can be null * @param args the arguments to pass to the constructor, can be null * @return the transformer * @throws IllegalArgumentException if the paramTypes and args don't match * @see org.apache.commons.collections15.functors.InstantiateTransformer */ public static Transformer instantiateTransformer(Class[] paramTypes, Object[] args) { return InstantiateTransformer.getInstance(paramTypes, args); } /** * Creates a Transformer that uses the passed in Map to transform the input * object (as a simple lookup). * * @param map the map to use to transform the objects * @return the transformer * @throws IllegalArgumentException if the map is null * @see org.apache.commons.collections15.functors.MapTransformer */ public static Transformer mapTransformer(Map map) { return MapTransformer.getInstance(map); } /** * Gets a Transformer that invokes a method on the input object. * The method must have no parameters. If the input object is null, * null is returned. *

                  * For example, TransformerUtils.invokerTransformer("getName"); * will call the getName/code> method on the input object to * determine the transformer result. *

                  * Note: no type saftey provided by Java 1.5. * * @param methodName the method name to call on the input object, may not be null * @return the transformer * @throws IllegalArgumentException if the methodName is null. * @see org.apache.commons.collections15.functors.InvokerTransformer */ public static Transformer invokerTransformer(String methodName) { return InvokerTransformer.getInstance(methodName, null, null); } /** * Gets a Transformer that invokes a method on the input object. * The method parameters are specified. If the input object is null, * null is returned. *

                  * Note: no type saftey provided by Java 1.5. * * @param methodName the name of the method * @param paramTypes the parameter types * @param args the arguments * @return the transformer * @throws IllegalArgumentException if the method name is null * @throws IllegalArgumentException if the paramTypes and args don't match * @see org.apache.commons.collections15.functors.InvokerTransformer */ public static Transformer invokerTransformer(String methodName, Class[] paramTypes, Object[] args) { return InvokerTransformer.getInstance(methodName, paramTypes, args); } /** * Gets a transformer that returns a java.lang.String * representation of the input object. This is achieved via the * toString method, null returns 'null'. * * @return the transformer * @see org.apache.commons.collections15.functors.StringValueTransformer */ public static Transformer stringValueTransformer() { return StringValueTransformer.getInstance(); } } collections-generic-4.01/src/java/org/apache/commons/collections15/MapIterator.java0000644000175000017500000000771410464140763030563 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15; import java.util.Iterator; /** * Defines an iterator that operates over a Map. *

                  * This iterator is a special version designed for maps. It can be more * efficient to use this rather than an entry set iterator where the option * is available, and it is certainly more convenient. *

                  * A map that provides this interface may not hold the data internally using * Map Entry objects, thus this interface can avoid lots of object creation. *

                  * In use, this iterator iterates through the keys in the map. After each call * to next(), the getValue() method provides direct * access to the value. The value can also be set using setValue(). *

                   * MapIterator it = map.mapIterator();
                   * while (it.hasNext()) {
                   *   Object key = it.next();
                   *   Object value = it.getValue();
                   *   it.setValue(newValue);
                   * }
                   * 
                  * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:19 $ * @since Commons Collections 3.0 */ public interface MapIterator extends Iterator { /** * Checks to see if there are more entries still to be iterated. * * @return true if the iterator has more elements */ boolean hasNext(); /** * Gets the next key from the Map. * * @return the next key in the iteration * @throws java.util.NoSuchElementException * if the iteration is finished */ K next(); //----------------------------------------------------------------------- /** * Gets the current key, which is the key returned by the last call * to next(). * * @return the current key * @throws IllegalStateException if next() has not yet been called */ K getKey(); /** * Gets the current value, which is the value associated with the last key * returned by next(). * * @return the current value * @throws IllegalStateException if next() has not yet been called */ V getValue(); //----------------------------------------------------------------------- /** * Removes the last returned key from the underlying Map (optional operation). *

                  * This method can be called once per call to next(). * * @throws UnsupportedOperationException if remove is not supported by the map * @throws IllegalStateException if next() has not yet been called * @throws IllegalStateException if remove() has already been called * since the last call to next() */ void remove(); /** * Sets the value associated with the current key (optional operation). * * @param value the new value * @return the previous value * @throws UnsupportedOperationException if setValue is not supported by the map * @throws IllegalStateException if next() has not yet been called * @throws IllegalStateException if remove() has been called since the * last call to next() */ V setValue(V value); } collections-generic-4.01/src/java/org/apache/commons/collections15/iterators/0000755000175000017500000000000011664401370027471 5ustar giovannigiovanni././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootcollections-generic-4.01/src/java/org/apache/commons/collections15/iterators/EntrySetMapIterator.javacollections-generic-4.01/src/java/org/apache/commons/collections15/iterators/EntrySetMapIterator.jav0000644000175000017500000001302210464140756034123 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.iterators; import org.apache.commons.collections15.MapIterator; import org.apache.commons.collections15.ResettableIterator; import java.util.Iterator; import java.util.Map; /** * Implements a MapIterator using a Map entrySet. * Reverse iteration is not supported. *

                   * MapIterator it = map.mapIterator();
                   * while (it.hasNext()) {
                   *   Object key = it.next();
                   *   Object value = it.getValue();
                   *   it.setValue(newValue);
                   * }
                   * 
                  * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:24 $ * @since Commons Collections 3.0 */ public class EntrySetMapIterator implements MapIterator, ResettableIterator { private final Map map; private Iterator> iterator; private Map.Entry last; private boolean canRemove = false; /** * Constructor. * * @param map the map to iterate over */ public EntrySetMapIterator(Map map) { super(); this.map = map; this.iterator = map.entrySet().iterator(); } //----------------------------------------------------------------------- /** * Checks to see if there are more entries still to be iterated. * * @return true if the iterator has more elements */ public boolean hasNext() { return iterator.hasNext(); } /** * Gets the next key from the Map. * * @return the next key in the iteration * @throws java.util.NoSuchElementException * if the iteration is finished */ public K next() { last = iterator.next(); canRemove = true; return last.getKey(); } //----------------------------------------------------------------------- /** * Removes the last returned key from the underlying Map. *

                  * This method can be called once per call to next(). * * @throws UnsupportedOperationException if remove is not supported by the map * @throws IllegalStateException if next() has not yet been called * @throws IllegalStateException if remove() has already been called * since the last call to next() */ public void remove() { if (canRemove == false) { throw new IllegalStateException("Iterator remove() can only be called once after next()"); } iterator.remove(); last = null; canRemove = false; } //----------------------------------------------------------------------- /** * Gets the current key, which is the key returned by the last call * to next(). * * @return the current key * @throws IllegalStateException if next() has not yet been called */ public K getKey() { if (last == null) { throw new IllegalStateException("Iterator getKey() can only be called after next() and before remove()"); } return last.getKey(); } /** * Gets the current value, which is the value associated with the last key * returned by next(). * * @return the current value * @throws IllegalStateException if next() has not yet been called */ public V getValue() { if (last == null) { throw new IllegalStateException("Iterator getValue() can only be called after next() and before remove()"); } return last.getValue(); } /** * Sets the value associated with the current key. * * @param value the new value * @return the previous value * @throws UnsupportedOperationException if setValue is not supported by the map * @throws IllegalStateException if next() has not yet been called * @throws IllegalStateException if remove() has been called since the * last call to next() */ public V setValue(V value) { if (last == null) { throw new IllegalStateException("Iterator setValue() can only be called after next() and before remove()"); } return last.setValue(value); } //----------------------------------------------------------------------- /** * Resets the state of the iterator. */ public void reset() { iterator = map.entrySet().iterator(); last = null; canRemove = false; } /** * Gets the iterator as a String. * * @return a string version of the iterator */ public String toString() { if (last != null) { return "MapIterator[" + getKey() + "=" + getValue() + "]"; } else { return "MapIterator[]"; } } } ././@LongLink0000000000000000000000000000016600000000000011570 Lustar rootrootcollections-generic-4.01/src/java/org/apache/commons/collections15/iterators/AbstractOrderedMapIteratorDecorator.javacollections-generic-4.01/src/java/org/apache/commons/collections15/iterators/AbstractOrderedMapItera0000644000175000017500000000520410464140763034113 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.iterators; import org.apache.commons.collections15.OrderedMapIterator; /** * Provides basic behaviour for decorating an ordered map iterator with extra functionality. *

                  * All methods are forwarded to the decorated map iterator. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:24 $ * @since Commons Collections 3.0 */ public class AbstractOrderedMapIteratorDecorator implements OrderedMapIterator { /** * The iterator being decorated */ protected final OrderedMapIterator iterator; //----------------------------------------------------------------------- /** * Constructor that decorates the specified iterator. * * @param iterator the iterator to decorate, must not be null * @throws IllegalArgumentException if the collection is null */ public AbstractOrderedMapIteratorDecorator(OrderedMapIterator iterator) { super(); if (iterator == null) { throw new IllegalArgumentException("OrderedMapIterator must not be null"); } this.iterator = iterator; } /** * Gets the iterator being decorated. * * @return the decorated iterator */ protected OrderedMapIterator getOrderedMapIterator() { return iterator; } //----------------------------------------------------------------------- public boolean hasNext() { return iterator.hasNext(); } public K next() { return iterator.next(); } public boolean hasPrevious() { return iterator.hasPrevious(); } public K previous() { return iterator.previous(); } public void remove() { iterator.remove(); } public K getKey() { return iterator.getKey(); } public V getValue() { return iterator.getValue(); } public V setValue(V obj) { return iterator.setValue(obj); } } ././@LongLink0000000000000000000000000000015700000000000011570 Lustar rootrootcollections-generic-4.01/src/java/org/apache/commons/collections15/iterators/AbstractMapIteratorDecorator.javacollections-generic-4.01/src/java/org/apache/commons/collections15/iterators/AbstractMapIteratorDeco0000644000175000017500000000464610464140754034137 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.iterators; import org.apache.commons.collections15.MapIterator; /** * Provides basic behaviour for decorating a map iterator with extra functionality. *

                  * All methods are forwarded to the decorated map iterator. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:24 $ * @since Commons Collections 3.0 */ public class AbstractMapIteratorDecorator implements MapIterator { /** * The iterator being decorated */ protected final MapIterator iterator; //----------------------------------------------------------------------- /** * Constructor that decorates the specified iterator. * * @param iterator the iterator to decorate, must not be null * @throws IllegalArgumentException if the collection is null */ public AbstractMapIteratorDecorator(MapIterator iterator) { super(); if (iterator == null) { throw new IllegalArgumentException("MapIterator must not be null"); } this.iterator = iterator; } /** * Gets the iterator being decorated. * * @return the decorated iterator */ protected MapIterator getMapIterator() { return iterator; } //----------------------------------------------------------------------- public boolean hasNext() { return iterator.hasNext(); } public K next() { return iterator.next(); } public void remove() { iterator.remove(); } public K getKey() { return iterator.getKey(); } public V getValue() { return iterator.getValue(); } public V setValue(V obj) { return iterator.setValue(obj); } } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootcollections-generic-4.01/src/java/org/apache/commons/collections15/iterators/EmptyOrderedIterator.javacollections-generic-4.01/src/java/org/apache/commons/collections15/iterators/EmptyOrderedIterator.ja0000644000175000017500000000265710464140763034137 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.iterators; import org.apache.commons.collections15.OrderedIterator; import org.apache.commons.collections15.ResettableIterator; /** * Provides an implementation of an empty ordered iterator. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:24 $ * @since Commons Collections 3.1 */ public class EmptyOrderedIterator extends AbstractEmptyIterator implements OrderedIterator, ResettableIterator { /** * Singleton instance of the iterator. * * @since Commons Collections 3.1 */ public static final OrderedIterator INSTANCE = new EmptyOrderedIterator(); /** * Constructor. */ protected EmptyOrderedIterator() { super(); } } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootcollections-generic-4.01/src/java/org/apache/commons/collections15/iterators/UniqueFilterIterator.javacollections-generic-4.01/src/java/org/apache/commons/collections15/iterators/UniqueFilterIterator.ja0000644000175000017500000000300510464140760034131 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 1999-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.iterators; import org.apache.commons.collections15.functors.UniquePredicate; import java.util.Iterator; /** * A FilterIterator which only returns "unique" Objects. Internally, * the Iterator maintains a Set of objects it has already encountered, * and duplicate Objects are skipped. * * @author Matt Hall, John Watkinson, Morgan Delagrange * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:24 $ * @since Commons Collections 2.1 */ public class UniqueFilterIterator extends FilterIterator { //------------------------------------------------------------------------- /** * Constructs a new UniqueFilterIterator. * * @param iterator the iterator to use */ public UniqueFilterIterator(Iterator iterator) { super(iterator, UniquePredicate.getInstance()); } } ././@LongLink0000000000000000000000000000016100000000000011563 Lustar rootrootcollections-generic-4.01/src/java/org/apache/commons/collections15/iterators/UnmodifiableOrderedMapIterator.javacollections-generic-4.01/src/java/org/apache/commons/collections15/iterators/UnmodifiableOrderedMapI0000644000175000017500000000564010464140761034074 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 1999-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.iterators; import org.apache.commons.collections15.OrderedMapIterator; import org.apache.commons.collections15.Unmodifiable; /** * Decorates an ordered map iterator such that it cannot be modified. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:24 $ * @since Commons Collections 3.0 */ public final class UnmodifiableOrderedMapIterator implements OrderedMapIterator, Unmodifiable { /** * The iterator being decorated */ private OrderedMapIterator iterator; //----------------------------------------------------------------------- /** * Decorates the specified iterator such that it cannot be modified. * * @param iterator the iterator to decorate * @throws IllegalArgumentException if the iterator is null */ public static OrderedMapIterator decorate(OrderedMapIterator iterator) { if (iterator == null) { throw new IllegalArgumentException("OrderedMapIterator must not be null"); } if (iterator instanceof Unmodifiable) { return iterator; } return new UnmodifiableOrderedMapIterator(iterator); } //----------------------------------------------------------------------- /** * Constructor. * * @param iterator the iterator to decorate */ private UnmodifiableOrderedMapIterator(OrderedMapIterator iterator) { super(); this.iterator = iterator; } //----------------------------------------------------------------------- public boolean hasNext() { return iterator.hasNext(); } public K next() { return iterator.next(); } public boolean hasPrevious() { return iterator.hasPrevious(); } public K previous() { return iterator.previous(); } public K getKey() { return iterator.getKey(); } public V getValue() { return iterator.getValue(); } public V setValue(V value) { throw new UnsupportedOperationException("setValue() is not supported"); } public void remove() { throw new UnsupportedOperationException("remove() is not supported"); } } collections-generic-4.01/src/java/org/apache/commons/collections15/iterators/LoopingIterator.java0000644000175000017500000001022210464140761033453 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 1999-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.iterators; import org.apache.commons.collections15.ResettableIterator; import java.util.Collection; import java.util.Iterator; import java.util.NoSuchElementException; /** * An Iterator that restarts when it reaches the end. *

                  * The iterator will loop continuously around the provided elements, unless * there are no elements in the collection to begin with, or all the elements * have been {@link #remove removed}. *

                  * Concurrent modifications are not directly supported, and for most collection * implementations will throw a ConcurrentModificationException. * * @author Jonathan Carlson * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:24 $ * @since Commons Collections 3.0 */ public class LoopingIterator implements ResettableIterator { /** * The collection to base the iterator on */ private Collection collection; /** * The current iterator */ private Iterator iterator; /** * Constructor that wraps a collection. *

                  * There is no way to reset an Iterator instance without recreating it from * the original source, so the Collection must be passed in. * * @param coll the collection to wrap * @throws NullPointerException if the collection is null */ public LoopingIterator(Collection coll) { if (coll == null) { throw new NullPointerException("The collection must not be null"); } collection = coll; reset(); } /** * Has the iterator any more elements. *

                  * Returns false only if the collection originally had zero elements, or * all the elements have been {@link #remove removed}. * * @return true if there are more elements */ public boolean hasNext() { return (collection.size() > 0); } /** * Returns the next object in the collection. *

                  * If at the end of the collection, return the first element. * * @throws NoSuchElementException if there are no elements * at all. Use {@link #hasNext} to avoid this error. */ public E next() { if (collection.size() == 0) { throw new NoSuchElementException("There are no elements for this iterator to loop on"); } if (iterator.hasNext() == false) { reset(); } return iterator.next(); } /** * Removes the previously retrieved item from the underlying collection. *

                  * This feature is only supported if the underlying collection's * {@link Collection#iterator iterator} method returns an implementation * that supports it. *

                  * This method can only be called after at least one {@link #next} method call. * After a removal, the remove method may not be called again until another * next has been performed. If the {@link #reset} is called, then remove may * not be called until {@link #next} is called again. */ public void remove() { iterator.remove(); } /** * Resets the iterator back to the start of the collection. */ public void reset() { iterator = collection.iterator(); } /** * Gets the size of the collection underlying the iterator. * * @return the current collection size */ public int size() { return collection.size(); } } collections-generic-4.01/src/java/org/apache/commons/collections15/iterators/ArrayListIterator.java0000644000175000017500000001651010464140754033766 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 1999-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.iterators; import org.apache.commons.collections15.ResettableListIterator; import java.lang.reflect.Array; import java.util.ListIterator; import java.util.NoSuchElementException; /** * Implements a {@link ListIterator} over an array. *

                  * The array can be either an array of object or of primitives. If you know * that you have an object array, the {@link ObjectArrayListIterator} * class is a better choice, as it will perform better. *

                  *

                  * This iterator does not support {@link #add(Object)} or {@link #remove()}, as the array * cannot be changed in size. The {@link #set(Object)} method is supported however. * * @author Neil O'Toole * @author Stephen Colebourne * @author Matt Hall, John Watkinson, Phil Steitz * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:24 $ * @see org.apache.commons.collections15.iterators.ArrayIterator * @see java.util.Iterator * @see java.util.ListIterator * @since Commons Collections 3.0 */ public class ArrayListIterator extends ArrayIterator implements ListIterator, ResettableListIterator { /** * Holds the index of the last item returned by a call to next() * or previous(). This is set to -1 if neither method * has yet been invoked. lastItemIndex is used to to implement * the {@link #set} method. */ protected int lastItemIndex = -1; // Constructors // ---------------------------------------------------------------------- /** * Constructor for use with setArray. *

                  * Using this constructor, the iterator is equivalent to an empty iterator * until {@link #setArray(Object)} is called to establish the array to iterate over. */ public ArrayListIterator() { super(); } /** * Constructs an ArrayListIterator that will iterate over the values in the * specified array. * * @param array the array to iterate over * @throws IllegalArgumentException if array is not an array. * @throws NullPointerException if array is null */ public ArrayListIterator(Object array) { super(array); } /** * Constructs an ArrayListIterator that will iterate over the values in the * specified array from a specific start index. * * @param array the array to iterate over * @param startIndex the index to start iterating at * @throws IllegalArgumentException if array is not an array. * @throws NullPointerException if array is null * @throws IndexOutOfBoundsException if the start index is out of bounds */ public ArrayListIterator(Object array, int startIndex) { super(array, startIndex); this.startIndex = startIndex; } /** * Construct an ArrayListIterator that will iterate over a range of values * in the specified array. * * @param array the array to iterate over * @param startIndex the index to start iterating at * @param endIndex the index (exclusive) to finish iterating at * @throws IllegalArgumentException if array is not an array. * @throws IndexOutOfBoundsException if the start or end index is out of bounds * @throws IllegalArgumentException if end index is before the start * @throws NullPointerException if array is null */ public ArrayListIterator(Object array, int startIndex, int endIndex) { super(array, startIndex, endIndex); this.startIndex = startIndex; } // ListIterator interface //----------------------------------------------------------------------- /** * Returns true if there are previous elements to return from the array. * * @return true if there is a previous element to return */ public boolean hasPrevious() { return (this.index > this.startIndex); } /** * Gets the previous element from the array. * * @return the previous element * @throws NoSuchElementException if there is no previous element */ public E previous() { if (hasPrevious() == false) { throw new NoSuchElementException(); } this.lastItemIndex = --this.index; return (E) Array.get(this.array, this.index); } /** * Gets the next element from the array. * * @return the next element * @throws NoSuchElementException if there is no next element */ public E next() { if (hasNext() == false) { throw new NoSuchElementException(); } this.lastItemIndex = this.index; return (E) Array.get(this.array, this.index++); } /** * Gets the next index to be retrieved. * * @return the index of the item to be retrieved next */ public int nextIndex() { return this.index - this.startIndex; } /** * Gets the index of the item to be retrieved if {@link #previous()} is called. * * @return the index of the item to be retrieved next */ public int previousIndex() { return this.index - this.startIndex - 1; } /** * This iterator does not support modification of its backing collection, and so will * always throw an {@link UnsupportedOperationException} when this method is invoked. * * @throws UnsupportedOperationException always thrown. * @see java.util.ListIterator#set */ public void add(E o) { throw new UnsupportedOperationException("add() method is not supported"); } /** * Sets the element under the cursor. *

                  * This method sets the element that was returned by the last call * to {@link #next()} of {@link #previous()}. *

                  * Note: {@link ListIterator} implementations that support * add() and remove() only allow set() to be called * once per call to next() or previous (see the {@link ListIterator} * javadoc for more details). Since this implementation does * not support add() or remove(), set() may be * called as often as desired. * * @see java.util.ListIterator#set */ public void set(E o) { if (this.lastItemIndex == -1) { throw new IllegalStateException("must call next() or previous() before a call to set()"); } Array.set(this.array, this.lastItemIndex, o); } /** * Resets the iterator back to the start index. */ public void reset() { super.reset(); this.lastItemIndex = -1; } } ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootcollections-generic-4.01/src/java/org/apache/commons/collections15/iterators/AbstractEmptyIterator.javacollections-generic-4.01/src/java/org/apache/commons/collections15/iterators/AbstractEmptyIterator.j0000644000175000017500000000435010464140756034147 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.iterators; import java.util.NoSuchElementException; /** * Provides an implementation of an empty iterator. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:24 $ * @since Commons Collections 3.1 */ abstract class AbstractEmptyIterator { /** * Constructor. */ protected AbstractEmptyIterator() { super(); } public boolean hasNext() { return false; } public E next() { throw new NoSuchElementException("Iterator contains no elements"); } public boolean hasPrevious() { return false; } public E previous() { throw new NoSuchElementException("Iterator contains no elements"); } public int nextIndex() { return 0; } public int previousIndex() { return -1; } public void add(E obj) { throw new UnsupportedOperationException("add() not supported for empty Iterator"); } public void set(E obj) { throw new IllegalStateException("Iterator contains no elements"); } public void remove() { throw new IllegalStateException("Iterator contains no elements"); } public E getKey() { throw new IllegalStateException("Iterator contains no elements"); } public E getValue() { throw new IllegalStateException("Iterator contains no elements"); } public E setValue(E value) { throw new IllegalStateException("Iterator contains no elements"); } public void reset() { // do nothing } } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootcollections-generic-4.01/src/java/org/apache/commons/collections15/iterators/IteratorEnumeration.javacollections-generic-4.01/src/java/org/apache/commons/collections15/iterators/IteratorEnumeration.jav0000644000175000017500000000553410464140763034205 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 1999-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.iterators; import java.util.Enumeration; import java.util.Iterator; /** * Adapter to make an {@link Iterator Iterator} instance appear to be * an {@link Enumeration Enumeration} instance. * * @author Matt Hall, John Watkinson, James Strachan * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:24 $ * @since Commons Collections 1.0 */ public class IteratorEnumeration implements Enumeration { /** * The iterator being decorated. */ private Iterator iterator; /** * Constructs a new IteratorEnumeration that will not * function until {@link #setIterator(Iterator) setIterator} is * invoked. */ public IteratorEnumeration() { super(); } /** * Constructs a new IteratorEnumeration that will use * the given iterator. * * @param iterator the iterator to use */ public IteratorEnumeration(Iterator iterator) { super(); this.iterator = iterator; } // Iterator interface //------------------------------------------------------------------------- /** * Returns true if the underlying iterator has more elements. * * @return true if the underlying iterator has more elements */ public boolean hasMoreElements() { return iterator.hasNext(); } /** * Returns the next element from the underlying iterator. * * @return the next element from the underlying iterator. * @throws java.util.NoSuchElementException * if the underlying iterator has no * more elements */ public E nextElement() { return iterator.next(); } // Properties //------------------------------------------------------------------------- /** * Returns the underlying iterator. * * @return the underlying iterator */ public Iterator getIterator() { return iterator; } /** * Sets the underlying iterator. * * @param iterator the new underlying iterator */ public void setIterator(Iterator iterator) { this.iterator = iterator; } } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootcollections-generic-4.01/src/java/org/apache/commons/collections15/iterators/UnmodifiableIterator.javacollections-generic-4.01/src/java/org/apache/commons/collections15/iterators/UnmodifiableIterator.ja0000644000175000017500000000470410464140764034126 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 1999-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.iterators; import org.apache.commons.collections15.Unmodifiable; import java.util.Iterator; /** * Decorates an iterator such that it cannot be modified. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:24 $ * @since Commons Collections 3.0 */ public final class UnmodifiableIterator implements Iterator, Unmodifiable { /** * The iterator being decorated */ private Iterator iterator; //----------------------------------------------------------------------- /** * Decorates the specified iterator such that it cannot be modified. *

                  * If the iterator is already unmodifiable it is returned directly. * * @param iterator the iterator to decorate * @throws IllegalArgumentException if the iterator is null */ public static Iterator decorate(Iterator iterator) { if (iterator == null) { throw new IllegalArgumentException("Iterator must not be null"); } if (iterator instanceof Unmodifiable) { return iterator; } return new UnmodifiableIterator(iterator); } //----------------------------------------------------------------------- /** * Constructor. * * @param iterator the iterator to decorate */ private UnmodifiableIterator(Iterator iterator) { super(); this.iterator = iterator; } //----------------------------------------------------------------------- public boolean hasNext() { return iterator.hasNext(); } public E next() { return iterator.next(); } public void remove() { throw new UnsupportedOperationException("remove() is not supported"); } } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootcollections-generic-4.01/src/java/org/apache/commons/collections15/iterators/EnumerationIterator.javacollections-generic-4.01/src/java/org/apache/commons/collections15/iterators/EnumerationIterator.jav0000644000175000017500000001113410464140763034176 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 1999-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.iterators; import java.util.Collection; import java.util.Enumeration; import java.util.Iterator; /** * Adapter to make {@link Enumeration Enumeration} instances appear * to be {@link Iterator Iterator} instances. * * @author James Strachan * @author Matt Hall, John Watkinson, Daniel Rall * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:24 $ * @since Commons Collections 1.0 */ public class EnumerationIterator implements Iterator { /** * The collection to remove elements from */ private Collection collection; /** * The enumeration being converted */ private Enumeration enumeration; /** * The last object retrieved */ private E last; // Constructors //----------------------------------------------------------------------- /** * Constructs a new EnumerationIterator that will not * function until {@link #setEnumeration(Enumeration)} is called. */ public EnumerationIterator() { this(null, null); } /** * Constructs a new EnumerationIterator that provides * an iterator view of the given enumeration. * * @param enumeration the enumeration to use */ public EnumerationIterator(final Enumeration enumeration) { this(enumeration, null); } /** * Constructs a new EnumerationIterator that will remove * elements from the specified collection. * * @param enumeration the enumeration to use * @param collection the collection to remove elements form */ public EnumerationIterator(final Enumeration enumeration, final Collection collection) { super(); this.enumeration = enumeration; this.collection = collection; this.last = null; } // Iterator interface //----------------------------------------------------------------------- /** * Returns true if the underlying enumeration has more elements. * * @return true if the underlying enumeration has more elements * @throws NullPointerException if the underlying enumeration is null */ public boolean hasNext() { return enumeration.hasMoreElements(); } /** * Returns the next object from the enumeration. * * @return the next object from the enumeration * @throws NullPointerException if the enumeration is null */ public E next() { last = enumeration.nextElement(); return last; } /** * Removes the last retrieved element if a collection is attached. *

                  * Functions if an associated Collection is known. * If so, the first occurrence of the last returned object from this * iterator will be removed from the collection. * * @throws IllegalStateException next() not called. * @throws UnsupportedOperationException if no associated collection */ public void remove() { if (collection != null) { if (last != null) { collection.remove(last); } else { throw new IllegalStateException("next() must have been called for remove() to function"); } } else { throw new UnsupportedOperationException("No Collection associated with this Iterator"); } } // Properties //----------------------------------------------------------------------- /** * Returns the underlying enumeration. * * @return the underlying enumeration */ public Enumeration getEnumeration() { return enumeration; } /** * Sets the underlying enumeration. * * @param enumeration the new underlying enumeration */ public void setEnumeration(final Enumeration enumeration) { this.enumeration = enumeration; } } collections-generic-4.01/src/java/org/apache/commons/collections15/iterators/TransformIterator.java0000644000175000017500000001110010464140756034017 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 1999-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.iterators; import org.apache.commons.collections15.Transformer; import java.util.Iterator; /** * Decorates an iterator such that each element returned is transformed. * * @author James Strachan * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:24 $ * @since Commons Collections 1.0 */ public class TransformIterator implements Iterator { /** * The iterator being used */ private Iterator iterator; /** * The transformer being used */ private Transformer transformer; //----------------------------------------------------------------------- /** * Constructs a new TransformIterator that will not function * until the {@link #setIterator(Iterator) setIterator} method is * invoked. */ public TransformIterator() { super(); } /** * Constructs a new TransformIterator that won't transform * elements from the given iterator. * * @param iterator the iterator to use */ public TransformIterator(Iterator iterator) { super(); this.iterator = iterator; } /** * Constructs a new TransformIterator that will use the * given iterator and transformer. If the given transformer is null, * then objects will not be transformed. * * @param iterator the iterator to use * @param transformer the transformer to use */ public TransformIterator(Iterator iterator, Transformer transformer) { super(); this.iterator = iterator; this.transformer = transformer; } //----------------------------------------------------------------------- public boolean hasNext() { return iterator.hasNext(); } /** * Gets the next object from the iteration, transforming it using the * current transformer. If the transformer is null, no transformation * occurs and the object from the iterator is returned directly. * * @return the next object * @throws java.util.NoSuchElementException * if there are no more elements */ public O next() { return transform(iterator.next()); } public void remove() { iterator.remove(); } //----------------------------------------------------------------------- /** * Gets the iterator this iterator is using. * * @return the iterator. */ public Iterator getIterator() { return iterator; } /** * Sets the iterator for this iterator to use. * If iteration has started, this effectively resets the iterator. * * @param iterator the iterator to use */ public void setIterator(Iterator iterator) { this.iterator = iterator; } //----------------------------------------------------------------------- /** * Gets the transformer this iterator is using. * * @return the transformer. */ public Transformer getTransformer() { return transformer; } /** * Sets the transformer this the iterator to use. * A null transformer is a no-op transformer. * * @param transformer the transformer to use */ public void setTransformer(Transformer transformer) { this.transformer = transformer; } //----------------------------------------------------------------------- /** * Transforms the given object using the transformer. * If the transformer is null, the original object is returned as-is. * * @param source the object to transform * @return the transformed object */ protected O transform(I source) { if (transformer != null) { return transformer.transform(source); } // Generics hack Object sourceObj = source; return (O) sourceObj; } } ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootcollections-generic-4.01/src/java/org/apache/commons/collections15/iterators/SingletonListIterator.javacollections-generic-4.01/src/java/org/apache/commons/collections15/iterators/SingletonListIterator.j0000644000175000017500000001220210464140760034151 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 1999-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.iterators; import org.apache.commons.collections15.ResettableListIterator; import java.util.ListIterator; import java.util.NoSuchElementException; /** * SingletonIterator is an {@link ListIterator} over a single * object instance. * * @author Stephen Colebourne * @author Matt Hall, John Watkinson, Rodney Waldhoff * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:24 $ * @since Commons Collections 2.1 */ public class SingletonListIterator implements ListIterator, ResettableListIterator { private boolean beforeFirst = true; private boolean nextCalled = false; private boolean removed = false; private E object; /** * Constructs a new SingletonListIterator. * * @param object the single object to return from the iterator */ public SingletonListIterator(E object) { super(); this.object = object; } /** * Is another object available from the iterator? *

                  * This returns true if the single object hasn't been returned yet. * * @return true if the single object hasn't been returned yet */ public boolean hasNext() { return beforeFirst && !removed; } /** * Is a previous object available from the iterator? *

                  * This returns true if the single object has been returned. * * @return true if the single object has been returned */ public boolean hasPrevious() { return !beforeFirst && !removed; } /** * Returns the index of the element that would be returned by a subsequent * call to next. * * @return 0 or 1 depending on current state. */ public int nextIndex() { return (beforeFirst ? 0 : 1); } /** * Returns the index of the element that would be returned by a subsequent * call to previous. A return value of -1 indicates that the iterator is currently at * the start. * * @return 0 or -1 depending on current state. */ public int previousIndex() { return (beforeFirst ? -1 : 0); } /** * Get the next object from the iterator. *

                  * This returns the single object if it hasn't been returned yet. * * @return the single object * @throws NoSuchElementException if the single object has already * been returned */ public E next() { if (!beforeFirst || removed) { throw new NoSuchElementException(); } beforeFirst = false; nextCalled = true; return object; } /** * Get the previous object from the iterator. *

                  * This returns the single object if it has been returned. * * @return the single object * @throws NoSuchElementException if the single object has not already * been returned */ public E previous() { if (beforeFirst || removed) { throw new NoSuchElementException(); } beforeFirst = true; return object; } /** * Remove the object from this iterator. * * @throws IllegalStateException if the next or previous * method has not yet been called, or the remove method * has already been called after the last call to next * or previous. */ public void remove() { if (!nextCalled || removed) { throw new IllegalStateException(); } else { object = null; removed = true; } } /** * Add always throws {@link UnsupportedOperationException}. * * @throws UnsupportedOperationException always */ public void add(E obj) { throw new UnsupportedOperationException("add() is not supported by this iterator"); } /** * Set sets the value of the singleton. * * @param obj the object to set * @throws IllegalStateException if next has not been called * or the object has been removed */ public void set(E obj) { if (!nextCalled || removed) { throw new IllegalStateException(); } this.object = obj; } /** * Reset the iterator back to the start. */ public void reset() { beforeFirst = true; nextCalled = false; } } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootcollections-generic-4.01/src/java/org/apache/commons/collections15/iterators/ObjectGraphIterator.javacollections-generic-4.01/src/java/org/apache/commons/collections15/iterators/ObjectGraphIterator.jav0000644000175000017500000002150010464140765034100 0ustar giovannigiovanni// GenericsNote: Won't be converted, not type safe. /* * Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.iterators; import org.apache.commons.collections15.ArrayStack; import org.apache.commons.collections15.Transformer; import java.util.Iterator; import java.util.NoSuchElementException; /** * An Iterator that can traverse multiple iterators down an object graph. *

                  * This iterator can extract multiple objects from a complex tree-like object graph. * The iteration starts from a single root object. * It uses a Transformer to extract the iterators and elements. * Its main benefit is that no intermediate List is created. *

                  * For example, consider an object graph: *

                   *                 |- Branch -- Leaf
                   *                 |         \- Leaf
                   *         |- Tree |         /- Leaf
                   *         |       |- Branch -- Leaf
                   *  Forest |                 \- Leaf
                   *         |       |- Branch -- Leaf
                   *         |       |         \- Leaf
                   *         |- Tree |         /- Leaf
                   *                 |- Branch -- Leaf
                   *                 |- Branch -- Leaf
                  * The following Transformer, used in this class, will extract all * the Leaf objects without creating a combined intermediate list: *
                   * public Object transform(Object input) {
                   *   if (input instanceof Forest) {
                   *     return ((Forest) input).treeIterator();
                   *   }
                   *   if (input instanceof Tree) {
                   *     return ((Tree) input).branchIterator();
                   *   }
                   *   if (input instanceof Branch) {
                   *     return ((Branch) input).leafIterator();
                   *   }
                   *   if (input instanceof Leaf) {
                   *     return input;
                   *   }
                   *   throw new ClassCastException();
                   * }
                  *

                  * Internally, iteration starts from the root object. When next is called, * the transformer is called to examine the object. The transformer will return * either an iterator or an object. If the object is an Iterator, the next element * from that iterator is obtained and the process repeats. If the element is an object * it is returned. *

                  * Under many circumstances, linking Iterators together in this manner is * more efficient (and convenient) than using nested for loops to extract a list. *

                  * Note: this class is not type-safe in Java 1.5 (no generics). *

                  * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:24 $ * @since Commons Collections 3.1 */ public class ObjectGraphIterator implements Iterator { /** * The stack of iterators */ protected final ArrayStack stack = new ArrayStack(8); /** * The root object in the tree */ protected Object root; /** * The transformer to use */ protected Transformer transformer; /** * Whether there is another element in the iteration */ protected boolean hasNext = false; /** * The current iterator */ protected Iterator currentIterator; /** * The current value */ protected Object currentValue; /** * The last used iterator, needed for remove() */ protected Iterator lastUsedIterator; //----------------------------------------------------------------------- /** * Constructs an ObjectGraphIterator using a root object and transformer. *

                  * The root object can be an iterator, in which case it will be immediately * looped around. * * @param root the root object, null will result in an empty iterator * @param transformer the transformer to use, null will use a no effect transformer */ public ObjectGraphIterator(Object root, Transformer transformer) { super(); if (root instanceof Iterator) { this.currentIterator = (Iterator) root; } else { this.root = root; } this.transformer = transformer; } /** * Constructs a ObjectGraphIterator that will handle an iterator of iterators. *

                  * This constructor exists for convenience to emphasise that this class can * be used to iterate over nested iterators. That is to say that the iterator * passed in here contains other iterators, which may in turn contain further * iterators. * * @param rootIterator the root iterator, null will result in an empty iterator */ public ObjectGraphIterator(Iterator rootIterator) { super(); this.currentIterator = rootIterator; this.transformer = null; } //----------------------------------------------------------------------- /** * Loops around the iterators to find the next value to return. */ protected void updateCurrentIterator() { if (hasNext) { return; } if (currentIterator == null) { if (root == null) { // do nothing, hasNext will be false } else { if (transformer == null) { findNext(root); } else { findNext(transformer.transform(root)); } root = null; } } else { findNextByIterator(currentIterator); } } /** * Finds the next object in the iteration given any start object. * * @param value the value to start from */ protected void findNext(Object value) { if (value instanceof Iterator) { // need to examine this iterator findNextByIterator((Iterator) value); } else { // next value found currentValue = value; hasNext = true; } } /** * Finds the next object in the iteration given an iterator. * * @param iterator the iterator to start from */ protected void findNextByIterator(Iterator iterator) { if (iterator != currentIterator) { // recurse a level if (currentIterator != null) { stack.push(currentIterator); } currentIterator = iterator; } while (currentIterator.hasNext() && hasNext == false) { Object next = currentIterator.next(); if (transformer != null) { next = transformer.transform(next); } findNext(next); } if (hasNext) { // next value found } else if (stack.isEmpty()) { // all iterators exhausted } else { // current iterator exhausted, go up a level currentIterator = (Iterator) stack.pop(); findNextByIterator(currentIterator); } } //----------------------------------------------------------------------- /** * Checks whether there are any more elements in the iteration to obtain. * * @return true if elements remain in the iteration */ public boolean hasNext() { updateCurrentIterator(); return hasNext; } /** * Gets the next element of the iteration. * * @return the next element from the iteration * @throws NoSuchElementException if all the Iterators are exhausted */ public Object next() { updateCurrentIterator(); if (hasNext == false) { throw new NoSuchElementException("No more elements in the iteration"); } lastUsedIterator = currentIterator; Object result = currentValue; currentValue = null; hasNext = false; return result; } /** * Removes from the underlying collection the last element returned. *

                  * This method calls remove() on the underlying Iterator and it may * throw an UnsupportedOperationException if the underlying Iterator * does not support this method. * * @throws UnsupportedOperationException if the remove operator is not supported by the underlying Iterator * @throws IllegalStateException if the next method has not yet been called, or the remove method has * already been called after the last call to the next method. */ public void remove() { if (lastUsedIterator == null) { throw new IllegalStateException("Iterator remove() cannot be called at this time"); } lastUsedIterator.remove(); lastUsedIterator = null; } } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootcollections-generic-4.01/src/java/org/apache/commons/collections15/iterators/ListIteratorWrapper.javacollections-generic-4.01/src/java/org/apache/commons/collections15/iterators/ListIteratorWrapper.jav0000644000175000017500000001207610464140764034173 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 1999-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.iterators; import java.util.Iterator; import java.util.LinkedList; import java.util.ListIterator; import java.util.NoSuchElementException; /** * As the wrapped Iterator is traversed, ListIteratorWrapper * builds a LinkedList of its values, permitting all required * operations of ListIterator. * * @author Morgan Delagrange * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:24 $ * @since Commons Collections 2.1 */ public class ListIteratorWrapper implements ListIterator { /** * Holds value of property "iterator" */ private final Iterator iterator; private final LinkedList list = new LinkedList(); // position of this iterator private int currentIndex = 0; // position of the wrapped iterator // this Iterator should only be used to populate the list private int wrappedIteratorIndex = 0; private static final String UNSUPPORTED_OPERATION_MESSAGE = "ListIteratorWrapper does not support optional operations of ListIterator."; // Constructor //------------------------------------------------------------------------- /** * Constructs a new ListIteratorWrapper that will wrap * the given iterator. * * @param iterator the iterator to wrap * @throws NullPointerException if the iterator is null */ public ListIteratorWrapper(Iterator iterator) { super(); if (iterator == null) { throw new NullPointerException("Iterator must not be null"); } this.iterator = iterator; } // ListIterator interface //------------------------------------------------------------------------- /** * Throws {@link UnsupportedOperationException}. * * @param o ignored * @throws UnsupportedOperationException always */ public void add(E o) throws UnsupportedOperationException { throw new UnsupportedOperationException(UNSUPPORTED_OPERATION_MESSAGE); } /** * Returns true if there are more elements in the iterator. * * @return true if there are more elements */ public boolean hasNext() { if (currentIndex == wrappedIteratorIndex) { return iterator.hasNext(); } return true; } /** * Returns true if there are previous elements in the iterator. * * @return true if there are previous elements */ public boolean hasPrevious() { if (currentIndex == 0) { return false; } return true; } /** * Returns the next element from the iterator. * * @return the next element from the iterator * @throws NoSuchElementException if there are no more elements */ public E next() throws NoSuchElementException { if (currentIndex < wrappedIteratorIndex) { ++currentIndex; return list.get(currentIndex - 1); } E retval = iterator.next(); list.add(retval); ++currentIndex; ++wrappedIteratorIndex; return retval; } /** * Returns in the index of the next element. * * @return the index of the next element */ public int nextIndex() { return currentIndex; } /** * Returns the the previous element. * * @return the previous element * @throws NoSuchElementException if there are no previous elements */ public E previous() throws NoSuchElementException { if (currentIndex == 0) { throw new NoSuchElementException(); } --currentIndex; return list.get(currentIndex); } /** * Returns the index of the previous element. * * @return the index of the previous element */ public int previousIndex() { return currentIndex - 1; } /** * Throws {@link UnsupportedOperationException}. * * @throws UnsupportedOperationException always */ public void remove() throws UnsupportedOperationException { throw new UnsupportedOperationException(UNSUPPORTED_OPERATION_MESSAGE); } /** * Throws {@link UnsupportedOperationException}. * * @param o ignored * @throws UnsupportedOperationException always */ public void set(E o) throws UnsupportedOperationException { throw new UnsupportedOperationException(UNSUPPORTED_OPERATION_MESSAGE); } } ././@LongLink0000000000000000000000000000016000000000000011562 Lustar rootrootcollections-generic-4.01/src/java/org/apache/commons/collections15/iterators/AbstractListIteratorDecorator.javacollections-generic-4.01/src/java/org/apache/commons/collections15/iterators/AbstractListIteratorDec0000644000175000017500000000520210464140763034143 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.iterators; import java.util.ListIterator; /** * Provides basic behaviour for decorating a list iterator with extra functionality. *

                  * All methods are forwarded to the decorated list iterator. * * @author Rodney Waldhoff * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:24 $ * @since Commons Collections 3.0 */ public class AbstractListIteratorDecorator implements ListIterator { /** * The iterator being decorated */ protected final ListIterator iterator; //----------------------------------------------------------------------- /** * Constructor that decorates the specified iterator. * * @param iterator the iterator to decorate, must not be null * @throws IllegalArgumentException if the collection is null */ public AbstractListIteratorDecorator(ListIterator iterator) { super(); if (iterator == null) { throw new IllegalArgumentException("ListIterator must not be null"); } this.iterator = iterator; } /** * Gets the iterator being decorated. * * @return the decorated iterator */ protected ListIterator getListIterator() { return iterator; } //----------------------------------------------------------------------- public boolean hasNext() { return iterator.hasNext(); } public E next() { return iterator.next(); } public int nextIndex() { return iterator.nextIndex(); } public boolean hasPrevious() { return iterator.hasPrevious(); } public E previous() { return iterator.previous(); } public int previousIndex() { return iterator.previousIndex(); } public void remove() { iterator.remove(); } public void set(E obj) { iterator.set(obj); } public void add(E obj) { iterator.add(obj); } } collections-generic-4.01/src/java/org/apache/commons/collections15/iterators/EmptyIterator.java0000644000175000017500000000350610464140760033150 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.iterators; import org.apache.commons.collections15.ResettableIterator; import java.util.Iterator; /** * Provides an implementation of an empty iterator. *

                  * This class provides an implementation of an empty iterator. * This class provides for binary compatability between Commons Collections * 2.1.1 and 3.1 due to issues with IteratorUtils. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:24 $ * @since Commons Collections 2.1.1 and 3.1 */ public class EmptyIterator extends AbstractEmptyIterator implements ResettableIterator { /** * Singleton instance of the iterator. * * @since Commons Collections 3.1 */ public static final ResettableIterator RESETTABLE_INSTANCE = new EmptyIterator(); /** * Singleton instance of the iterator. * * @since Commons Collections 2.1.1 and 3.1 */ public static final Iterator INSTANCE = RESETTABLE_INSTANCE; public static Iterator getInstance() { return INSTANCE; } /** * Constructor. */ protected EmptyIterator() { super(); } } collections-generic-4.01/src/java/org/apache/commons/collections15/iterators/FilterIterator.java0000644000175000017500000001313610464140764033303 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 1999-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.iterators; import org.apache.commons.collections15.Predicate; import java.util.Iterator; import java.util.NoSuchElementException; /** * Decorates an iterator such that only elements matching a predicate filter * are returned. * * @author James Strachan * @author Jan Sorensen * @author Ralph Wagner * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:24 $ * @since Commons Collections 1.0 */ public class FilterIterator implements Iterator { /** * The iterator being used */ private Iterator iterator; /** * The predicate being used */ private Predicate predicate; /** * The next object in the iteration */ private E nextObject; /** * Whether the next object has been calculated yet */ private boolean nextObjectSet = false; //----------------------------------------------------------------------- /** * Constructs a new FilterIterator that will not function * until {@link #setIterator(Iterator) setIterator} is invoked. */ public FilterIterator() { super(); } /** * Constructs a new FilterIterator that will not function * until {@link #setPredicate(Predicate) setPredicate} is invoked. * * @param iterator the iterator to use */ public FilterIterator(Iterator iterator) { super(); this.iterator = iterator; } /** * Constructs a new FilterIterator that will use the * given iterator and predicate. * * @param iterator the iterator to use * @param predicate the predicate to use */ public FilterIterator(Iterator iterator, Predicate predicate) { super(); this.iterator = iterator; this.predicate = predicate; } //----------------------------------------------------------------------- /** * Returns true if the underlying iterator contains an object that * matches the predicate. * * @return true if there is another object that matches the predicate */ public boolean hasNext() { if (nextObjectSet) { return true; } else { return setNextObject(); } } /** * Returns the next object that matches the predicate. * * @return the next object which matches the given predicate * @throws NoSuchElementException if there are no more elements that * match the predicate */ public E next() { if (!nextObjectSet) { if (!setNextObject()) { throw new NoSuchElementException(); } } nextObjectSet = false; return nextObject; } /** * Removes from the underlying collection of the base iterator the last * element returned by this iterator. * This method can only be called * if next() was called, but not after * hasNext(), because the hasNext() call * changes the base iterator. * * @throws IllegalStateException if hasNext() has already * been called. */ public void remove() { if (nextObjectSet) { throw new IllegalStateException("remove() cannot be called"); } iterator.remove(); } //----------------------------------------------------------------------- /** * Gets the iterator this iterator is using. * * @return the iterator. */ public Iterator getIterator() { return iterator; } /** * Sets the iterator for this iterator to use. * If iteration has started, this effectively resets the iterator. * * @param iterator the iterator to use */ public void setIterator(Iterator iterator) { this.iterator = iterator; } //----------------------------------------------------------------------- /** * Gets the predicate this iterator is using. * * @return the predicate. */ public Predicate getPredicate() { return predicate; } /** * Sets the predicate this the iterator to use. * * @param predicate the transformer to use */ public void setPredicate(Predicate predicate) { this.predicate = predicate; } //----------------------------------------------------------------------- /** * Set nextObject to the next object. If there are no more * objects then return false. Otherwise, return true. */ private boolean setNextObject() { while (iterator.hasNext()) { E object = iterator.next(); if (predicate.evaluate(object)) { nextObject = object; nextObjectSet = true; return true; } } return false; } } collections-generic-4.01/src/java/org/apache/commons/collections15/iterators/EmptyMapIterator.java0000644000175000017500000000260610464140755033612 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.iterators; import org.apache.commons.collections15.MapIterator; import org.apache.commons.collections15.ResettableIterator; /** * Provides an implementation of an empty map iterator. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:24 $ * @since Commons Collections 3.1 */ public class EmptyMapIterator extends AbstractEmptyIterator implements MapIterator, ResettableIterator { /** * Singleton instance of the iterator. * * @since Commons Collections 3.1 */ public static final MapIterator INSTANCE = new EmptyMapIterator(); /** * Constructor. */ protected EmptyMapIterator() { super(); } } ././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootcollections-generic-4.01/src/java/org/apache/commons/collections15/iterators/UnmodifiableListIterator.javacollections-generic-4.01/src/java/org/apache/commons/collections15/iterators/UnmodifiableListIterato0000644000175000017500000000565210464140756034213 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 1999-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.iterators; import org.apache.commons.collections15.Unmodifiable; import java.util.ListIterator; /** * Decorates a list iterator such that it cannot be modified. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:24 $ * @since Commons Collections 3.0 */ public final class UnmodifiableListIterator implements ListIterator, Unmodifiable { /** * The iterator being decorated */ private ListIterator iterator; //----------------------------------------------------------------------- /** * Decorates the specified iterator such that it cannot be modified. * * @param iterator the iterator to decorate * @throws IllegalArgumentException if the iterator is null */ public static ListIterator decorate(ListIterator iterator) { if (iterator == null) { throw new IllegalArgumentException("ListIterator must not be null"); } if (iterator instanceof Unmodifiable) { return iterator; } return new UnmodifiableListIterator(iterator); } //----------------------------------------------------------------------- /** * Constructor. * * @param iterator the iterator to decorate */ private UnmodifiableListIterator(ListIterator iterator) { super(); this.iterator = iterator; } //----------------------------------------------------------------------- public boolean hasNext() { return iterator.hasNext(); } public E next() { return iterator.next(); } public int nextIndex() { return iterator.nextIndex(); } public boolean hasPrevious() { return iterator.hasPrevious(); } public E previous() { return iterator.previous(); } public int previousIndex() { return iterator.previousIndex(); } public void remove() { throw new UnsupportedOperationException("remove() is not supported"); } public void set(E obj) { throw new UnsupportedOperationException("set() is not supported"); } public void add(E obj) { throw new UnsupportedOperationException("add() is not supported"); } } collections-generic-4.01/src/java/org/apache/commons/collections15/iterators/FilterListIterator.java0000644000175000017500000001735310464140762034142 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 1999-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.iterators; import org.apache.commons.collections15.Predicate; import java.util.ListIterator; import java.util.NoSuchElementException; /** * A proxy {@link ListIterator ListIterator} which * takes a {@link Predicate Predicate} instance to filter * out objects from an underlying ListIterator * instance. Only objects for which the specified * Predicate evaluates to true are * returned by the iterator. * * @author Matt Hall, John Watkinson, Rodney Waldhoff * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:24 $ * @since Commons Collections 2.0 */ public class FilterListIterator implements ListIterator { /** * The iterator being used */ private ListIterator iterator; /** * The predicate being used */ private Predicate predicate; /** * The value of the next (matching) object, when * {@link #nextObjectSet} is true. */ private E nextObject; /** * Whether or not the {@link #nextObject} has been set * (possibly to null). */ private boolean nextObjectSet = false; /** * The value of the previous (matching) object, when * {@link #previousObjectSet} is true. */ private E previousObject; /** * Whether or not the {@link #previousObject} has been set * (possibly to null). */ private boolean previousObjectSet = false; /** * The index of the element that would be returned by {@link #next}. */ private int nextIndex = 0; //----------------------------------------------------------------------- /** * Constructs a new FilterListIterator that will not * function until * {@link #setPredicate(Predicate) setPredicate} is invoked. */ public FilterListIterator() { super(); } /** * Constructs a new FilterListIterator that will not * function until {@link #setPredicate(Predicate) setPredicate} is invoked. * * @param iterator the iterator to use */ public FilterListIterator(ListIterator iterator) { super(); this.iterator = iterator; } /** * Constructs a new FilterListIterator. * * @param iterator the iterator to use * @param predicate the predicate to use */ public FilterListIterator(ListIterator iterator, Predicate predicate) { super(); this.iterator = iterator; this.predicate = predicate; } /** * Constructs a new FilterListIterator. * * @param predicate the predicate to use. */ public FilterListIterator(Predicate predicate) { super(); this.predicate = predicate; } //----------------------------------------------------------------------- /** * Not supported. */ public void add(E o) { throw new UnsupportedOperationException("FilterListIterator.add(Object) is not supported."); } public boolean hasNext() { if (nextObjectSet) { return true; } else { return setNextObject(); } } public boolean hasPrevious() { if (previousObjectSet) { return true; } else { return setPreviousObject(); } } public E next() { if (!nextObjectSet) { if (!setNextObject()) { throw new NoSuchElementException(); } } nextIndex++; E temp = nextObject; clearNextObject(); return temp; } public int nextIndex() { return nextIndex; } public E previous() { if (!previousObjectSet) { if (!setPreviousObject()) { throw new NoSuchElementException(); } } nextIndex--; E temp = previousObject; clearPreviousObject(); return temp; } public int previousIndex() { return (nextIndex - 1); } /** * Not supported. */ public void remove() { throw new UnsupportedOperationException("FilterListIterator.remove() is not supported."); } /** * Not supported. */ public void set(E o) { throw new UnsupportedOperationException("FilterListIterator.set(Object) is not supported."); } //----------------------------------------------------------------------- /** * Gets the iterator this iterator is using. * * @return the iterator. */ public ListIterator getListIterator() { return iterator; } /** * Sets the iterator for this iterator to use. * If iteration has started, this effectively resets the iterator. * * @param iterator the iterator to use */ public void setListIterator(ListIterator iterator) { this.iterator = iterator; } //----------------------------------------------------------------------- /** * Gets the predicate this iterator is using. * * @return the predicate. */ public Predicate getPredicate() { return predicate; } /** * Sets the predicate this the iterator to use. * * @param predicate the transformer to use */ public void setPredicate(Predicate predicate) { this.predicate = predicate; } //----------------------------------------------------------------------- private void clearNextObject() { nextObject = null; nextObjectSet = false; } private boolean setNextObject() { // if previousObjectSet, // then we've walked back one step in the // underlying list (due to a hasPrevious() call) // so skip ahead one matching object if (previousObjectSet) { clearPreviousObject(); if (!setNextObject()) { return false; } else { clearNextObject(); } } while (iterator.hasNext()) { E object = iterator.next(); if (predicate.evaluate(object)) { nextObject = object; nextObjectSet = true; return true; } } return false; } private void clearPreviousObject() { previousObject = null; previousObjectSet = false; } private boolean setPreviousObject() { // if nextObjectSet, // then we've walked back one step in the // underlying list (due to a hasNext() call) // so skip ahead one matching object if (nextObjectSet) { clearNextObject(); if (!setPreviousObject()) { return false; } else { clearPreviousObject(); } } while (iterator.hasPrevious()) { E object = iterator.previous(); if (predicate.evaluate(object)) { previousObject = object; previousObjectSet = true; return true; } } return false; } } collections-generic-4.01/src/java/org/apache/commons/collections15/iterators/ArrayIterator.java0000644000175000017500000001757710464140761033146 0ustar giovannigiovanni// GenericsNote: Converted, although unsatisfying because there does not seem to be a way to generify the primitive types. /* * Copyright 1999-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.iterators; import org.apache.commons.collections15.ResettableIterator; import java.lang.reflect.Array; import java.util.NoSuchElementException; /** * Implements an {@link java.util.Iterator Iterator} over any array. *

                  * The array can be either an array of object or of primitives. If you know * that you have an object array, the * {@link org.apache.commons.collections15.iterators.ObjectArrayIterator ObjectArrayIterator} * class is a better choice, as it will perform better. *

                  * The iterator implements a {@link #reset} method, allowing the reset of * the iterator back to the start if required. * * @author James Strachan * @author Mauricio S. Moura * @author Michael A. Smith * @author Neil O'Toole * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:24 $ * @since Commons Collections 1.0 */ public class ArrayIterator implements ResettableIterator { /** * The array to iterate over */ protected Object array; /** * The start index to loop from */ protected int startIndex = 0; /** * The end index to loop to */ protected int endIndex = 0; /** * The current iterator index */ protected int index = 0; // Constructors // ---------------------------------------------------------------------- /** * Constructor for use with setArray. *

                  * Using this constructor, the iterator is equivalent to an empty iterator * until {@link #setArray(Object)} is called to establish the array to iterate over. */ public ArrayIterator() { super(); } /** * Constructs an ArrayIterator that will iterate over the values in the * specified array. * * @param array the array to iterate over. * @throws IllegalArgumentException if array is not an array. * @throws NullPointerException if array is null */ public ArrayIterator(final Object array) { super(); setArray(array); } /** * Constructs an ArrayIterator that will iterate over the values in the * specified array from a specific start index. * * @param array the array to iterate over. * @param startIndex the index to start iterating at. * @throws IllegalArgumentException if array is not an array. * @throws NullPointerException if array is null * @throws IndexOutOfBoundsException if the index is invalid */ public ArrayIterator(final Object array, final int startIndex) { super(); setArray(array); checkBound(startIndex, "start"); this.startIndex = startIndex; this.index = startIndex; } /** * Construct an ArrayIterator that will iterate over a range of values * in the specified array. * * @param array the array to iterate over. * @param startIndex the index to start iterating at. * @param endIndex the index to finish iterating at. * @throws IllegalArgumentException if array is not an array. * @throws NullPointerException if array is null * @throws IndexOutOfBoundsException if either index is invalid */ public ArrayIterator(final Object array, final int startIndex, final int endIndex) { super(); setArray(array); checkBound(startIndex, "start"); checkBound(endIndex, "end"); if (endIndex < startIndex) { throw new IllegalArgumentException("End index must not be less than start index."); } this.startIndex = startIndex; this.endIndex = endIndex; this.index = startIndex; } /** * Checks whether the index is valid or not. * * @param bound the index to check * @param type the index type (for error messages) * @throws IndexOutOfBoundsException if the index is invalid */ protected void checkBound(final int bound, final String type) { if (bound > this.endIndex) { throw new ArrayIndexOutOfBoundsException("Attempt to make an ArrayIterator that " + type + "s beyond the end of the array. "); } if (bound < 0) { throw new ArrayIndexOutOfBoundsException("Attempt to make an ArrayIterator that " + type + "s before the start of the array. "); } } // Iterator interface //----------------------------------------------------------------------- /** * Returns true if there are more elements to return from the array. * * @return true if there is a next element to return */ public boolean hasNext() { return (index < endIndex); } /** * Returns the next element in the array. * * @return the next element in the array * @throws NoSuchElementException if all the elements in the array * have already been returned */ public E next() { if (hasNext() == false) { throw new NoSuchElementException(); } return (E) Array.get(array, index++); } /** * Throws {@link UnsupportedOperationException}. * * @throws UnsupportedOperationException always */ public void remove() { throw new UnsupportedOperationException("remove() method is not supported"); } // Properties //----------------------------------------------------------------------- /** * Gets the array that this iterator is iterating over. * * @return the array this iterator iterates over, or null if * the no-arg constructor was used and {@link #setArray(Object)} has never * been called with a valid array. */ public Object getArray() { return array; } /** * Sets the array that the ArrayIterator should iterate over. *

                  * If an array has previously been set (using the single-arg constructor * or this method) then that array is discarded in favour of this one. * Iteration is restarted at the start of the new array. * Although this can be used to reset iteration, the {@link #reset()} method * is a more effective choice. * * @param array the array that the iterator should iterate over. * @throws IllegalArgumentException if array is not an array. * @throws NullPointerException if array is null */ public void setArray(final Object array) { // Array.getLength throws IllegalArgumentException if the object is not // an array or NullPointerException if the object is null. This call // is made before saving the array and resetting the index so that the // array iterator remains in a consistent state if the argument is not // an array or is null. this.endIndex = Array.getLength(array); this.startIndex = 0; this.array = array; this.index = 0; } /** * Resets the iterator back to the start index. */ public void reset() { this.index = this.startIndex; } } ././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootcollections-generic-4.01/src/java/org/apache/commons/collections15/iterators/EmptyOrderedMapIterator.javacollections-generic-4.01/src/java/org/apache/commons/collections15/iterators/EmptyOrderedMapIterator0000644000175000017500000000267010464140765034201 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.iterators; import org.apache.commons.collections15.OrderedMapIterator; import org.apache.commons.collections15.ResettableIterator; /** * Provides an implementation of an empty ordered map iterator. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:24 $ * @since Commons Collections 3.1 */ public class EmptyOrderedMapIterator extends AbstractEmptyIterator implements OrderedMapIterator, ResettableIterator { /** * Singleton instance of the iterator. * * @since Commons Collections 3.1 */ public static final OrderedMapIterator INSTANCE = new EmptyOrderedMapIterator(); /** * Constructor. */ protected EmptyOrderedMapIterator() { super(); } } collections-generic-4.01/src/java/org/apache/commons/collections15/iterators/CollatingIterator.java0000644000175000017500000003057510464140756034001 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 1999-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.iterators; import org.apache.commons.collections15.list.UnmodifiableList; import java.util.*; /** * Provides an ordered iteration over the elements contained in * a collection of ordered Iterators. *

                  * Given two ordered {@link Iterator} instances A and B, * the {@link #next} method on this iterator will return the lesser of * A.next() and B.next(). * * @author Rodney Waldhoff * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:24 $ * @since Commons Collections 2.1 */ public class CollatingIterator implements Iterator { /** * The {@link Comparator} used to evaluate order. */ private Comparator comparator = null; /** * The list of {@link Iterator}s to evaluate. */ private ArrayList> iterators = null; /** * {@link Iterator#next Next} objects peeked from each iterator. */ private ArrayList values = null; /** * Whether or not each {@link #values} element has been set. */ private BitSet valueSet = null; /** * Index of the {@link #iterators iterator} from whom the last returned value was obtained. */ private int lastReturned = -1; // Constructors // ---------------------------------------------------------------------- /** * Constructs a new CollatingIterator. Natural sort order * will be used, and child iterators will have to be manually added * using the {@link #addIterator(Iterator)} method. */ public CollatingIterator() { this(null, 2); } /** * Constructs a new CollatingIterator that will used the * specified comparator for ordering. Child iterators will have to be * manually added using the {@link #addIterator(Iterator)} method. * * @param comp the comparator to use to sort, or null to use natural sort order */ public CollatingIterator(final Comparator comp) { this(comp, 2); } /** * Constructs a new CollatingIterator that will used the * specified comparator for ordering and have the specified initial * capacity. Child iterators will have to be * manually added using the {@link #addIterator(Iterator)} method. * * @param comp the comparator to use to sort, or null to use natural sort order * @param initIterCapacity the initial capacity for the internal list * of child iterators */ public CollatingIterator(final Comparator comp, final int initIterCapacity) { iterators = new ArrayList>(initIterCapacity); setComparator(comp); } /** * Constructs a new CollatingIterator that will use the * specified comparator to provide ordered iteration over the two * given iterators. * * @param comp the comparator to use to sort, or null to use natural sort order * @param a the first child ordered iterator * @param b the second child ordered iterator * @throws NullPointerException if either iterator is null */ public CollatingIterator(final Comparator comp, final Iterator a, final Iterator b) { this(comp, 2); addIterator(a); addIterator(b); } /** * Constructs a new CollatingIterator that will use the * specified comparator to provide ordered iteration over the array * of iterators. * * @param comp the comparator to use to sort, or null to use natural sort order * @param iterators the array of iterators * @throws NullPointerException if iterators array is or contains null */ public CollatingIterator(final Comparator comp, final Iterator[] iterators) { this(comp, iterators.length); for (int i = 0; i < iterators.length; i++) { addIterator(iterators[i]); } } /** * Constructs a new CollatingIterator that will use the * specified comparator to provide ordered iteration over the collection * of iterators. * * @param comp the comparator to use to sort, or null to use natural sort order * @param iterators the collection of iterators * @throws NullPointerException if the iterators collection is or contains null * @throws ClassCastException if the iterators collection contains an * element that's not an {@link Iterator} */ public CollatingIterator(final Comparator comp, final Collection> iterators) { this(comp, iterators.size()); for (Iterator> it = iterators.iterator(); it.hasNext();) { Iterator item = it.next(); addIterator(item); } } // Public Methods // ---------------------------------------------------------------------- /** * Adds the given {@link Iterator} to the iterators being collated. * * @param iterator the iterator to add to the collation, must not be null * @throws IllegalStateException if iteration has started * @throws NullPointerException if the iterator is null */ public void addIterator(final Iterator iterator) { checkNotStarted(); if (iterator == null) { throw new NullPointerException("Iterator must not be null"); } iterators.add(iterator); } /** * Sets the iterator at the given index. * * @param index index of the Iterator to replace * @param iterator Iterator to place at the given index * @throws IndexOutOfBoundsException if index < 0 or index > size() * @throws IllegalStateException if iteration has started * @throws NullPointerException if the iterator is null */ public void setIterator(final int index, final Iterator iterator) { checkNotStarted(); if (iterator == null) { throw new NullPointerException("Iterator must not be null"); } iterators.set(index, iterator); } /** * Gets the list of Iterators (unmodifiable). * * @return the unmodifiable list of iterators added */ public List> getIterators() { return UnmodifiableList.decorate(iterators); } /** * Gets the {@link Comparator} by which collatation occurs. */ public Comparator getComparator() { return comparator; } /** * Sets the {@link Comparator} by which collation occurs. * * @throws IllegalStateException if iteration has started */ public void setComparator(final Comparator comp) { checkNotStarted(); comparator = comp; } // Iterator Methods // ------------------------------------------------------------------- /** * Returns true if any child iterator has remaining elements. * * @return true if this iterator has remaining elements */ public boolean hasNext() { start(); return anyValueSet(valueSet) || anyHasNext(iterators); } /** * Returns the next ordered element from a child iterator. * * @return the next ordered element * @throws NoSuchElementException if no child iterator has any more elements */ public E next() throws NoSuchElementException { if (hasNext() == false) { throw new NoSuchElementException(); } int leastIndex = least(); if (leastIndex == -1) { throw new NoSuchElementException(); } else { E val = values.get(leastIndex); clear(leastIndex); lastReturned = leastIndex; return val; } } /** * Removes the last returned element from the child iterator that * produced it. * * @throws IllegalStateException if there is no last returned element, * or if the last returned element has already been removed */ public void remove() { if (lastReturned == -1) { throw new IllegalStateException("No value can be removed at present"); } Iterator it = iterators.get(lastReturned); it.remove(); } // Private Methods // ------------------------------------------------------------------- /** * Initializes the collating state if it hasn't been already. */ private void start() { if (values == null) { values = new ArrayList(iterators.size()); valueSet = new BitSet(iterators.size()); for (int i = 0; i < iterators.size(); i++) { values.add(null); valueSet.clear(i); } } } /** * Sets the {@link #values} and {@link #valueSet} attributes * at position i to the next value of the * {@link #iterators iterator} at position i, or * clear them if the ith iterator * has no next value. * * @return false iff there was no value to set */ private boolean set(int i) { Iterator it = iterators.get(i); if (it.hasNext()) { values.set(i, it.next()); valueSet.set(i); return true; } else { values.set(i, null); valueSet.clear(i); return false; } } /** * Clears the {@link #values} and {@link #valueSet} attributes * at position i. */ private void clear(int i) { values.set(i, null); valueSet.clear(i); } /** * Throws {@link IllegalStateException} if iteration has started * via {@link #start}. * * @throws IllegalStateException if iteration started */ private void checkNotStarted() throws IllegalStateException { if (values != null) { throw new IllegalStateException("Can't do that after next or hasNext has been called."); } } /** * Returns the index of the least element in {@link #values}, * {@link #set(int) setting} any uninitialized values. * * @throws IllegalStateException */ private int least() { int leastIndex = -1; E leastObject = null; for (int i = 0; i < values.size(); i++) { if (valueSet.get(i) == false) { set(i); } if (valueSet.get(i)) { if (leastIndex == -1) { leastIndex = i; leastObject = values.get(i); } else { E curObject = values.get(i); if (comparator.compare(curObject, leastObject) < 0) { leastObject = curObject; leastIndex = i; } } } } return leastIndex; } /** * Returns true iff any bit in the given set is * true. */ private boolean anyValueSet(BitSet set) { for (int i = 0; i < set.size(); i++) { if (set.get(i)) { return true; } } return false; } /** * Returns true iff any {@link Iterator} * in the given list has a next value. */ private boolean anyHasNext(ArrayList> iters) { for (int i = 0; i < iters.size(); i++) { Iterator it = iters.get(i); if (it.hasNext()) { return true; } } return false; } } ././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootcollections-generic-4.01/src/java/org/apache/commons/collections15/iterators/UnmodifiableMapIterator.javacollections-generic-4.01/src/java/org/apache/commons/collections15/iterators/UnmodifiableMapIterator0000644000175000017500000000527310464140757034177 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 1999-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.iterators; import org.apache.commons.collections15.MapIterator; import org.apache.commons.collections15.Unmodifiable; /** * Decorates a map iterator such that it cannot be modified. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:24 $ * @since Commons Collections 3.0 */ public final class UnmodifiableMapIterator implements MapIterator, Unmodifiable { /** * The iterator being decorated */ private MapIterator iterator; //----------------------------------------------------------------------- /** * Decorates the specified iterator such that it cannot be modified. * * @param iterator the iterator to decorate * @throws IllegalArgumentException if the iterator is null */ public static MapIterator decorate(MapIterator iterator) { if (iterator == null) { throw new IllegalArgumentException("MapIterator must not be null"); } if (iterator instanceof Unmodifiable) { return iterator; } return new UnmodifiableMapIterator(iterator); } //----------------------------------------------------------------------- /** * Constructor. * * @param iterator the iterator to decorate */ private UnmodifiableMapIterator(MapIterator iterator) { super(); this.iterator = iterator; } //----------------------------------------------------------------------- public boolean hasNext() { return iterator.hasNext(); } public K next() { return iterator.next(); } public K getKey() { return iterator.getKey(); } public V getValue() { return iterator.getValue(); } public V setValue(V value) { throw new UnsupportedOperationException("setValue() is not supported"); } public void remove() { throw new UnsupportedOperationException("remove() is not supported"); } } collections-generic-4.01/src/java/org/apache/commons/collections15/iterators/SingletonIterator.java0000644000175000017500000001004110464140764034010 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 1999-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.iterators; import org.apache.commons.collections15.ResettableIterator; import java.util.Iterator; import java.util.NoSuchElementException; /** * SingletonIterator is an {@link Iterator} over a single * object instance. * * @author James Strachan * @author Stephen Colebourne * @author Matt Hall, John Watkinson, Rodney Waldhoff * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:24 $ * @since Commons Collections 2.0 */ public class SingletonIterator implements Iterator, ResettableIterator { /** * Whether remove is allowed */ private final boolean removeAllowed; /** * Is the cursor before the first element */ private boolean beforeFirst = true; /** * Has the element been removed */ private boolean removed = false; /** * The object */ private E object; /** * Constructs a new SingletonIterator where remove * is a permitted operation. * * @param object the single object to return from the iterator */ public SingletonIterator(E object) { this(object, true); } /** * Constructs a new SingletonIterator optionally choosing if * remove is a permitted operation. * * @param object the single object to return from the iterator * @param removeAllowed true if remove is allowed * @since Commons Collections 3.1 */ public SingletonIterator(E object, boolean removeAllowed) { super(); this.object = object; this.removeAllowed = removeAllowed; } //----------------------------------------------------------------------- /** * Is another object available from the iterator? *

                  * This returns true if the single object hasn't been returned yet. * * @return true if the single object hasn't been returned yet */ public boolean hasNext() { return (beforeFirst && !removed); } /** * Get the next object from the iterator. *

                  * This returns the single object if it hasn't been returned yet. * * @return the single object * @throws NoSuchElementException if the single object has already * been returned */ public E next() { if (!beforeFirst || removed) { throw new NoSuchElementException(); } beforeFirst = false; return object; } /** * Remove the object from this iterator. * * @throws IllegalStateException if the next method has not * yet been called, or the remove method has already * been called after the last call to the next * method. * @throws UnsupportedOperationException if remove is not supported */ public void remove() { if (removeAllowed) { if (removed || beforeFirst) { throw new IllegalStateException(); } else { object = null; removed = true; } } else { throw new UnsupportedOperationException(); } } /** * Reset the iterator to the start. */ public void reset() { beforeFirst = true; } } collections-generic-4.01/src/java/org/apache/commons/collections15/iterators/package.html0000644000175000017500000000175110464140762031760 0ustar giovannigiovanni

                  This package contains implementations of the {@link java.util.Iterator Iterator} interface.

                  You may also consider using {@link org.apache.commons.collections.IteratorUtils IteratorUtils}, which is a single class that uses static methods to construct instances of the classes in this package. collections-generic-4.01/src/java/org/apache/commons/collections15/iterators/EmptyListIterator.java0000644000175000017500000000345110464140754034006 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.iterators; import org.apache.commons.collections15.ResettableListIterator; import java.util.ListIterator; /** * Provides an implementation of an empty list iterator. *

                  * This class provides an implementation of an empty list iterator. * This class provides for binary compatability between Commons Collections * 2.1.1 and 3.1 due to issues with IteratorUtils. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:24 $ * @since Commons Collections 2.1.1 and 3.1 */ public class EmptyListIterator extends AbstractEmptyIterator implements ResettableListIterator { /** * Singleton instance of the iterator. * * @since Commons Collections 3.1 */ public static final ResettableListIterator RESETTABLE_INSTANCE = new EmptyListIterator(); /** * Singleton instance of the iterator. * * @since Commons Collections 2.1.1 and 3.1 */ public static final ListIterator INSTANCE = RESETTABLE_INSTANCE; /** * Constructor. */ protected EmptyListIterator() { super(); } } ././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootcollections-generic-4.01/src/java/org/apache/commons/collections15/iterators/ObjectArrayListIterator.javacollections-generic-4.01/src/java/org/apache/commons/collections15/iterators/ObjectArrayListIterator0000644000175000017500000001566010464140757034205 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 1999-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.iterators; import org.apache.commons.collections15.ResettableListIterator; import java.util.ListIterator; import java.util.NoSuchElementException; /** * Implements a {@link ListIterator} over an array of objects. *

                  * This iterator does not support {@link #add} or {@link #remove}, as the object array * cannot be structurally modified. The {@link #set} method is supported however. *

                  * The iterator implements a {@link #reset} method, allowing the reset of the iterator * back to the start if required. * * @author Neil O'Toole * @author Stephen Colebourne * @author Matt Hall, John Watkinson, Phil Steitz * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:24 $ * @see org.apache.commons.collections15.iterators.ObjectArrayIterator * @see java.util.Iterator * @see java.util.ListIterator * @since Commons Collections 3.0 */ public class ObjectArrayListIterator extends ObjectArrayIterator implements ListIterator, ResettableListIterator { /** * Holds the index of the last item returned by a call to next() * or previous(). This is set to -1 if neither method * has yet been invoked. lastItemIndex is used to to implement the * {@link #set} method. */ protected int lastItemIndex = -1; /** * Constructor for use with setArray. *

                  * Using this constructor, the iterator is equivalent to an empty iterator * until {@link #setArray} is called to establish the array to iterate over. */ public ObjectArrayListIterator() { super(); } /** * Constructs an ObjectArrayListIterator that will iterate over the values in the * specified array. * * @param array the array to iterate over * @throws NullPointerException if array is null */ public ObjectArrayListIterator(E[] array) { super(array); } /** * Constructs an ObjectArrayListIterator that will iterate over the values in the * specified array from a specific start index. * * @param array the array to iterate over * @param start the index to start iterating at * @throws NullPointerException if array is null * @throws IndexOutOfBoundsException if the start index is out of bounds */ public ObjectArrayListIterator(E[] array, int start) { super(array, start); } /** * Construct an ObjectArrayListIterator that will iterate over a range of values * in the specified array. * * @param array the array to iterate over * @param start the index to start iterating at * @param end the index (exclusive) to finish iterating at * @throws IndexOutOfBoundsException if the start or end index is out of bounds * @throws IllegalArgumentException if end index is before the start * @throws NullPointerException if array is null */ public ObjectArrayListIterator(E[] array, int start, int end) { super(array, start, end); } // ListIterator interface //------------------------------------------------------------------------- /** * Returns true if there are previous elements to return from the array. * * @return true if there is a previous element to return */ public boolean hasPrevious() { return (this.index > this.startIndex); } /** * Gets the previous element from the array. * * @return the previous element * @throws NoSuchElementException if there is no previous element */ public E previous() { if (hasPrevious() == false) { throw new NoSuchElementException(); } this.lastItemIndex = --this.index; return this.array[this.index]; } /** * Gets the next element from the array. * * @return the next element * @throws NoSuchElementException if there is no next element */ public E next() { if (hasNext() == false) { throw new NoSuchElementException(); } this.lastItemIndex = this.index; return this.array[this.index++]; } /** * Gets the next index to be retrieved. * * @return the index of the item to be retrieved next */ public int nextIndex() { return this.index - this.startIndex; } /** * Gets the index of the item to be retrieved if {@link #previous()} is called. * * @return the index of the item to be retrieved next */ public int previousIndex() { return this.index - this.startIndex - 1; } /** * This iterator does not support modification of its backing array's size, and so will * always throw an {@link UnsupportedOperationException} when this method is invoked. * * @param obj the object to add * @throws UnsupportedOperationException always thrown. */ public void add(E obj) { throw new UnsupportedOperationException("add() method is not supported"); } /** * Sets the element under the cursor. *

                  * This method sets the element that was returned by the last call * to {@link #next()} of {@link #previous()}. *

                  * Note: {@link ListIterator} implementations that support add() * and remove() only allow set() to be called once per call * to next() or previous (see the {@link ListIterator} * javadoc for more details). Since this implementation does not support * add() or remove(), set() may be * called as often as desired. * * @param obj the object to set into the array * @throws IllegalStateException if next() has not yet been called. * @throws ClassCastException if the object type is unsuitable for the array */ public void set(E obj) { if (this.lastItemIndex == -1) { throw new IllegalStateException("must call next() or previous() before a call to set()"); } this.array[this.lastItemIndex] = obj; } /** * Resets the iterator back to the start index. */ public void reset() { super.reset(); this.lastItemIndex = -1; } } ././@LongLink0000000000000000000000000000015400000000000011565 Lustar rootrootcollections-generic-4.01/src/java/org/apache/commons/collections15/iterators/AbstractIteratorDecorator.javacollections-generic-4.01/src/java/org/apache/commons/collections15/iterators/AbstractIteratorDecorat0000644000175000017500000000424610464140761034202 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.iterators; import java.util.Iterator; /** * Provides basic behaviour for decorating an iterator with extra functionality. *

                  * All methods are forwarded to the decorated iterator. * * @author Matt Hall, John Watkinson, James Strachan * @author Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:24 $ * @since Commons Collections 3.0 */ public class AbstractIteratorDecorator implements Iterator { /** * The iterator being decorated */ protected final Iterator iterator; //----------------------------------------------------------------------- /** * Constructor that decorates the specified iterator. * * @param iterator the iterator to decorate, must not be null * @throws IllegalArgumentException if the collection is null */ public AbstractIteratorDecorator(Iterator iterator) { super(); if (iterator == null) { throw new IllegalArgumentException("Iterator must not be null"); } this.iterator = iterator; } /** * Gets the iterator being decorated. * * @return the decorated iterator */ protected Iterator getIterator() { return iterator; } //----------------------------------------------------------------------- public boolean hasNext() { return iterator.hasNext(); } public E next() { return iterator.next(); } public void remove() { iterator.remove(); } } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootcollections-generic-4.01/src/java/org/apache/commons/collections15/iterators/ObjectArrayIterator.javacollections-generic-4.01/src/java/org/apache/commons/collections15/iterators/ObjectArrayIterator.jav0000644000175000017500000001565110464140754034125 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 1999-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.iterators; import org.apache.commons.collections15.ResettableIterator; import java.util.Iterator; import java.util.NoSuchElementException; /** * An {@link Iterator} over an array of objects. *

                  * This iterator does not support {@link #remove}, as the object array cannot be * structurally modified. *

                  * The iterator implements a {@link #reset} method, allowing the reset of the iterator * back to the start if required. * * @author James Strachan * @author Mauricio S. Moura * @author Michael A. Smith * @author Neil O'Toole * @author Stephen Colebourne * @author Matt Hall, John Watkinson, Phil Steitz * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:24 $ * @since Commons Collections 3.0 */ public class ObjectArrayIterator implements Iterator, ResettableIterator { /** * The array */ protected E[] array = null; /** * The start index to loop from */ protected int startIndex = 0; /** * The end index to loop to */ protected int endIndex = 0; /** * The current iterator index */ protected int index = 0; /** * Constructor for use with setArray. *

                  * Using this constructor, the iterator is equivalent to an empty iterator * until {@link #setArray} is called to establish the array to iterate over. */ public ObjectArrayIterator() { super(); } /** * Constructs an ObjectArrayIterator that will iterate over the values in the * specified array. * * @param array the array to iterate over * @throws NullPointerException if array is null */ public ObjectArrayIterator(E[] array) { this(array, 0, array.length); } /** * Constructs an ObjectArrayIterator that will iterate over the values in the * specified array from a specific start index. * * @param array the array to iterate over * @param start the index to start iterating at * @throws NullPointerException if array is null * @throws IndexOutOfBoundsException if the start index is out of bounds */ public ObjectArrayIterator(E[] array, int start) { this(array, start, array.length); } /** * Construct an ObjectArrayIterator that will iterate over a range of values * in the specified array. * * @param array the array to iterate over * @param start the index to start iterating at * @param end the index (exclusive) to finish iterating at * @throws IndexOutOfBoundsException if the start or end index is out of bounds * @throws IllegalArgumentException if end index is before the start * @throws NullPointerException if array is null */ public ObjectArrayIterator(E[] array, int start, int end) { super(); if (start < 0) { throw new ArrayIndexOutOfBoundsException("Start index must not be less than zero"); } if (end > array.length) { throw new ArrayIndexOutOfBoundsException("End index must not be greater than the array length"); } if (start > array.length) { throw new ArrayIndexOutOfBoundsException("Start index must not be greater than the array length"); } if (end < start) { throw new IllegalArgumentException("End index must not be less than start index"); } this.array = array; this.startIndex = start; this.endIndex = end; this.index = start; } // Iterator interface //------------------------------------------------------------------------- /** * Returns true if there are more elements to return from the array. * * @return true if there is a next element to return */ public boolean hasNext() { return (this.index < this.endIndex); } /** * Returns the next element in the array. * * @return the next element in the array * @throws NoSuchElementException if all the elements in the array * have already been returned */ public E next() { if (hasNext() == false) { throw new NoSuchElementException(); } return this.array[this.index++]; } /** * Throws {@link UnsupportedOperationException}. * * @throws UnsupportedOperationException always */ public void remove() { throw new UnsupportedOperationException("remove() method is not supported for an ObjectArrayIterator"); } // Properties //------------------------------------------------------------------------- /** * Gets the array that this iterator is iterating over. * * @return the array this iterator iterates over, or null if * the no-arg constructor was used and {@link #setArray} has never * been called with a valid array. */ public E[] getArray() { return this.array; } /** * Sets the array that the ArrayIterator should iterate over. *

                  * This method may only be called once, otherwise an IllegalStateException * will occur. *

                  * The {@link #reset} method can be used to reset the iterator if required. * * @param array the array that the iterator should iterate over * @throws IllegalStateException if the array was set in the constructor * @throws NullPointerException if array is null */ public void setArray(E[] array) { if (this.array != null) { throw new IllegalStateException("The array to iterate over has already been set"); } this.array = array; this.startIndex = 0; this.endIndex = array.length; this.index = 0; } /** * Gets the start index to loop from. * * @return the start index */ public int getStartIndex() { return this.startIndex; } /** * Gets the end index to loop to. * * @return the end index */ public int getEndIndex() { return this.endIndex; } /** * Resets the iterator back to the start index. */ public void reset() { this.index = this.startIndex; } } collections-generic-4.01/src/java/org/apache/commons/collections15/iterators/IteratorChain.java0000644000175000017500000002335610464140756033106 0ustar giovannigiovanni// GenericsNote: Converted. // GenericsNote: Some questions about things like UnmodifiableList.decorate(iteratorChain); and so on /* * Copyright 1999-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.iterators; import org.apache.commons.collections15.list.UnmodifiableList; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; /** * An IteratorChain is an Iterator that wraps a number of Iterators. *

                  * This class makes multiple iterators look like one to the caller * When any method from the Iterator interface is called, the IteratorChain * will delegate to a single underlying Iterator. The IteratorChain will * invoke the Iterators in sequence until all Iterators are exhausted. *

                  * Under many circumstances, linking Iterators together in this manner is * more efficient (and convenient) than reading out the contents of each * Iterator into a List and creating a new Iterator. *

                  * Calling a method that adds new Iteratorafter a method in the Iterator * interface has been called will result in an UnsupportedOperationException. * Subclasses should take care to not alter the underlying List of Iterators. *

                  * NOTE: As from version 3.0, the IteratorChain may contain no * iterators. In this case the class will function as an empty iterator. * * @author Morgan Delagrange * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:24 $ * @since Commons Collections 2.1 */ public class IteratorChain implements Iterator { /** * The chain of iterators */ protected final List> iteratorChain = new ArrayList>(); /** * The index of the current iterator */ protected int currentIteratorIndex = 0; /** * The current iterator */ protected Iterator currentIterator = null; /** * The "last used" Iterator is the Iterator upon which * next() or hasNext() was most recently called * used for the remove() operation only */ protected Iterator lastUsedIterator = null; /** * ComparatorChain is "locked" after the first time * compare(Object,Object) is called */ protected boolean isLocked = false; //----------------------------------------------------------------------- /** * Construct an IteratorChain with no Iterators. *

                  * You will normally use {@link #addIterator(Iterator)} to add * some iterators after using this constructor. */ public IteratorChain() { super(); } /** * Construct an IteratorChain with a single Iterator. * * @param iterator first Iterator in the IteratorChain * @throws NullPointerException if the iterator is null */ public IteratorChain(Iterator iterator) { super(); addIterator(iterator); } /** * Constructs a new IteratorChain over the two * given iterators. * * @param a the first child iterator * @param b the second child iterator * @throws NullPointerException if either iterator is null */ public IteratorChain(Iterator a, Iterator b) { super(); addIterator(a); addIterator(b); } /** * Constructs a new IteratorChain over the array * of iterators. * * @param iterators the array of iterators * @throws NullPointerException if iterators array is or contains null */ public IteratorChain(Iterator[] iterators) { super(); for (int i = 0; i < iterators.length; i++) { addIterator(iterators[i]); } } /** * Constructs a new IteratorChain over the collection * of iterators. * * @param iterators the collection of iterators * @throws NullPointerException if iterators collection is or contains null * @throws ClassCastException if iterators collection doesn't contain an iterator */ public IteratorChain(Collection> iterators) { super(); for (Iterator iterator : iterators) { addIterator(iterator); } } //----------------------------------------------------------------------- /** * Add an Iterator to the end of the chain * * @param iterator Iterator to add * @throws IllegalStateException if I've already started iterating * @throws NullPointerException if the iterator is null */ public void addIterator(Iterator iterator) { checkLocked(); if (iterator == null) { throw new NullPointerException("Iterator must not be null"); } iteratorChain.add(iterator); } /** * Set the Iterator at the given index * * @param index index of the Iterator to replace * @param iterator Iterator to place at the given index * @throws IndexOutOfBoundsException if index < 0 or index > size() * @throws IllegalStateException if I've already started iterating * @throws NullPointerException if the iterator is null */ public void setIterator(int index, Iterator iterator) throws IndexOutOfBoundsException { checkLocked(); if (iterator == null) { throw new NullPointerException("Iterator must not be null"); } iteratorChain.set(index, iterator); } /** * Get the list of Iterators (unmodifiable) * * @return the unmodifiable list of iterators added */ public List> getIterators() { return UnmodifiableList.decorate(iteratorChain); } /** * Number of Iterators in the current IteratorChain. * * @return Iterator count */ public int size() { return iteratorChain.size(); } /** * Determine if modifications can still be made to the IteratorChain. * IteratorChains cannot be modified once they have executed a method * from the Iterator interface. * * @return true if IteratorChain cannot be modified, false if it can */ public boolean isLocked() { return isLocked; } /** * Checks whether the iterator chain is now locked and in use. */ private void checkLocked() { if (isLocked == true) { throw new UnsupportedOperationException("IteratorChain cannot be changed after the first use of a method from the Iterator interface"); } } /** * Lock the chain so no more iterators can be added. * This must be called from all Iterator interface methods. */ private void lockChain() { if (isLocked == false) { isLocked = true; } } /** * Updates the current iterator field to ensure that the current Iterator * is not exhausted */ protected void updateCurrentIterator() { if (currentIterator == null) { if (iteratorChain.isEmpty()) { currentIterator = EmptyIterator.INSTANCE; } else { currentIterator = iteratorChain.get(0); } // set last used iterator here, in case the user calls remove // before calling hasNext() or next() (although they shouldn't) lastUsedIterator = currentIterator; } while (currentIterator.hasNext() == false && currentIteratorIndex < iteratorChain.size() - 1) { currentIteratorIndex++; currentIterator = iteratorChain.get(currentIteratorIndex); } } //----------------------------------------------------------------------- /** * Return true if any Iterator in the IteratorChain has a remaining element. * * @return true if elements remain */ public boolean hasNext() { lockChain(); updateCurrentIterator(); lastUsedIterator = currentIterator; return currentIterator.hasNext(); } /** * Returns the next Object of the current Iterator * * @return Object from the current Iterator * @throws java.util.NoSuchElementException * if all the Iterators are exhausted */ public E next() { lockChain(); updateCurrentIterator(); lastUsedIterator = currentIterator; return currentIterator.next(); } /** * Removes from the underlying collection the last element * returned by the Iterator. As with next() and hasNext(), * this method calls remove() on the underlying Iterator. * Therefore, this method may throw an * UnsupportedOperationException if the underlying * Iterator does not support this method. * * @throws UnsupportedOperationException if the remove operator is not supported by the underlying Iterator * @throws IllegalStateException if the next method has not yet been called, or the remove method has * already been called after the last call to the next method. */ public void remove() { lockChain(); updateCurrentIterator(); lastUsedIterator.remove(); } } collections-generic-4.01/src/java/org/apache/commons/collections15/ArrayStack.java0000644000175000017500000001411610464140755030373 0ustar giovannigiovanni// GenericsNote: Converted. /* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15; import java.util.ArrayList; import java.util.EmptyStackException; /** * An implementation of the {@link java.util.Stack} API that is based on an * ArrayList instead of a Vector, so it is not * synchronized to protect against multi-threaded access. The implementation * is therefore operates faster in environments where you do not need to * worry about multiple thread contention. *

                  * The removal order of an ArrayStack is based on insertion * order: The most recently added element is removed first. The iteration * order is not the same as the removal order. The iterator returns * elements from the bottom up, whereas the {@link #remove()} method removes * them from the top down. *

                  * Unlike Stack, ArrayStack accepts null entries. * * @author Craig R. McClanahan * @author Paul Jack * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:19 $ * @see java.util.Stack * @since Commons Collections 1.0 */ public class ArrayStack extends ArrayList implements Buffer { /** * Ensure serialization compatibility */ private static final long serialVersionUID = 2130079159931574599L; /** * Constructs a new empty ArrayStack. The initial size * is controlled by ArrayList and is currently 10. */ public ArrayStack() { super(); } /** * Constructs a new empty ArrayStack with an initial size. * * @param initialSize the initial size to use * @throws IllegalArgumentException if the specified initial size * is negative */ public ArrayStack(int initialSize) { super(initialSize); } /** * Return true if this stack is currently empty. *

                  * This method exists for compatibility with java.util.Stack. * New users of this class should use isEmpty instead. * * @return true if the stack is currently empty */ public boolean empty() { return isEmpty(); } /** * Returns the top item off of this stack without removing it. * * @return the top item on the stack * @throws EmptyStackException if the stack is empty */ public E peek() throws EmptyStackException { int n = size(); if (n <= 0) { throw new EmptyStackException(); } else { return get(n - 1); } } /** * Returns the n'th item down (zero-relative) from the top of this * stack without removing it. * * @param n the number of items down to go * @return the n'th item on the stack, zero relative * @throws EmptyStackException if there are not enough items on the * stack to satisfy this request */ public E peek(int n) throws EmptyStackException { int m = (size() - n) - 1; if (m < 0) { throw new EmptyStackException(); } else { return get(m); } } /** * Pops the top item off of this stack and return it. * * @return the top item on the stack * @throws EmptyStackException if the stack is empty */ public E pop() throws EmptyStackException { int n = size(); if (n <= 0) { throw new EmptyStackException(); } else { return remove(n - 1); } } /** * Pushes a new item onto the top of this stack. The pushed item is also * returned. This is equivalent to calling add. * * @param item the item to be added * @return the item just pushed */ public E push(E item) { add(item); return item; } /** * Returns the one-based position of the distance from the top that the * specified object exists on this stack, where the top-most element is * considered to be at distance 1. If the object is not * present on the stack, return -1 instead. The * equals() method is used to compare to the items * in this stack. * * @param object the object to be searched for * @return the 1-based depth into the stack of the object, or -1 if not found */ public int search(E object) { int i = size() - 1; // Current index int n = 1; // Current distance while (i >= 0) { E current = get(i); if ((object == null && current == null) || (object != null && object.equals(current))) { return n; } i--; n++; } return -1; } /** * Returns the element on the top of the stack. * * @return the element on the top of the stack * @throws BufferUnderflowException if the stack is empty */ public E get() { int size = size(); if (size == 0) { throw new BufferUnderflowException(); } return get(size - 1); } /** * Removes the element on the top of the stack. * * @return the removed element * @throws BufferUnderflowException if the stack is empty */ public E remove() { int size = size(); if (size == 0) { throw new BufferUnderflowException(); } return remove(size - 1); } } collections-generic-4.01/src/java/org/apache/commons/collections15/BufferOverflowException.java0000644000175000017500000000421710464140764033144 0ustar giovannigiovanni// GenericsNote: No conversion needed. /* * Copyright 2002-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15; /** * The BufferOverflowException is used when the buffer's capacity has been * exceeded. * * @author Avalon * @author Berin Loritsch * @author Jeff Turner * @author Paul Jack * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:19 $ * @since Commons Collections 2.1 */ public class BufferOverflowException extends RuntimeException { /** * The root cause throwable */ private final Throwable throwable; /** * Constructs a new BufferOverflowException. */ public BufferOverflowException() { super(); throwable = null; } /** * Construct a new BufferOverflowException. * * @param message the detail message for this exception */ public BufferOverflowException(String message) { this(message, null); } /** * Construct a new BufferOverflowException. * * @param message the detail message for this exception * @param exception the root cause of the exception */ public BufferOverflowException(String message, Throwable exception) { super(message); throwable = exception; } /** * Gets the root cause of the exception. * * @return the root cause */ public final Throwable getCause() { return throwable; } } collections-generic-4.01/src/media/0000755000175000017500000000000011664401370017444 5ustar giovannigiovannicollections-generic-4.01/src/media/logo.xcf0000644000175000017500000006002410464140763021113 0ustar giovannigiovannigimp xcf file,dBB/ gimp-commentCreated with The GIMP1_@^}" Text Layer#2     Q/W"slx" j48U6qq1U89;98U99:9UU99UUU8 8⪪ qqUU88q8U88UUUUUq8UqUUUqUUU8qUqq88UU88q UqU8qUU q8UUUUU8U q8U8UqUqUqU8U8UUUUUUqqUU Uƪ8 8qUU8UU8UU UUq78U9UU9;98q9q84U53U8q2q80U8UU8UqqUU U UU Uq8UUUU8UUUUUUqUUqU8UUU8U8qUUU88q8qUUqU8UƪU UqUUUU  88qƪUUU8qqUq8U8UUUUqUUUU8 88UUU UU:q999U:U>UU8 8U8 U qqU8qq q8 8U8UU UUq8U8UUqUƪqUqUUU8U qq88qUq8Uqq8q  qUU88U8UU  U8U8U8UU8U8UUq8UqUq88UU8UU8UUq8q8UU8UUƪ8 qUU8 UU88U88UUUU⪪ƪUUUUU8UU8q  88UƪUU8g36Drop-Shadow#2k     L*.6J1G1S6fV#_,   976 5 5 "4 "*/4 ",5=4 )5AI4 !/=JT4%4CR\4 '7HWa *;L[e ->O^g   0AR`h     #3DUbh      '7HXch    +;L[eg  !#$%$!  !"$%&&$!!/@P^ff  #%&(*,./.+& !$&'()+-0221-'!&4DTafe #'*,-./036774/(!$),/00/0259:4,$",9IXcgc  '-1343347:==;6/(#!!%*058986446:?EIJG@7.'%(1?N\efa "+38;<:74347;>@>:4.*),07<@BA=9657BDA=831137;>=:620266/,+-15898656:@HOSSOH?7102:FR^de_TI?:;CO[dgbX )6BLQRNF<2*%#$(,/2346;BKSY[XQG=3-+/8ETaike[ND?AIT_fg`T$1@LUYWOD8-#"&*-17?IT\aa[QE8.(',7FVdmni^RHDFMXbgf^P +:IV]_YOB4'"(/8DP\dgd[O@3)#$+7FWenpj`TKGJQ\dhd[L "1BQ]cbZN>/"$.:HWcjkeYK;.$ "+8HYgopi_TLIMU_fhcXI'7IYdhe[L;+ ".50/16<@BA=71,+/8DR^fgaWJ> !/>MX_`\TJ@70*%!'2>JRVUOF=620258::72,&#$)2?MX_`[QE: '4ALTVUOH@81+&! )4>FKKGA;51001220,&!",8EOUVQI>4 *5?FJJGB<5/)# )29>@>:61.,++*(%!$/:CHIE>4+ (18<><94/*$&,1331.+(&$#!%/6:;71*# $)-//-*&"  $''&%"  #),,*%  ""                    ,)  (   '  '$!!$$" &21-' !(.12/)! &@?:2)!"*3;?@<4* &MLE;0& !)3>GLMG>1% %XVNB6+#"&/:GRXWQE7) %`]TG9-%$)3@NZ`_WJ;+ $eaWI:-&%+6ES_ecZL<+ "hcWH9-&&-9HWche[L;*  hbUF7+%'.;KZeieZJ8' g`RB4)%'0>N\fhcWF5$ f]O?1'$(3AQ_gg`SB1!     dYJ;.&%*5ETagf]O>-    !aUF7+%%,9HWcgdZK9)    ",_RB3)$&/0'$(2@P]ef_RB1##&),/35651+$ "$&')+-//.+(&'+4@XI:-%$*5DT`fe\N>.!!&+.147:>ACB=6-$"&)+--.02578740--2;HTE6*$%,9HWbgcYJ:+ &,269;=?CGKMLH@6,%!!$(-134332369<>=:6337@MQA3($&/=L[dfaVF7*!#*29?BDDEGJNRUTOG=3,)*.38;<:853369=??=965:CPM=/&$(2AP]ef_RC4)#"&-6?GKMMLKLOSWYXSKA93249?CDC?951026:==<866:DQI9-%$*6ET`ge]O@3*&(/9CMSWWTQOOQUXZYSLC=9:>DILKG@81,+,/36764349DQE6*$%-9IXbgcYL=2++0:EQZ_`^YUQPQTWWUPIC?>BHNSTPI?5,&##&*-..18CQA2($&/=M[dgbWI;2.09ER^fihc]VROPQRROJEA@CIQWZYSH<0& #%&&(.7CR=/'$(3AQ^ef_TF:217BP^ipqmf^VPMLLKJGC?>@GOX_`\SF8+  $+6DS:-&%+6EUage]QD946>KZhswvpf\SLHEDB@=:9;AJU_ee^SD4&!*7FU7,&'.;JXche[OB96:EScqz|xodXNGA>;963238AMZdih_QA0" +9IX6+')2?N\fhdYMA98>JZkxxm`SH@:62/,++.6AO]hmj`P?.    ,-  "/@P^5-+0:HWcjjcWK@;=ESds~tfWH=4-(%" ")3BRbmqlaP>.  %3DUb6/.3>L[fljbWJ@<>GUet~sdUF:1+&# !'2ARbmqmbRA1$P(7HXe6006AO]hljaUI@;>FTds}|rdUG;2,'#  &1?O_komcTD5) +;K[g6117CP^hkh`TG>:;CP`ny}zreWJ>5.)%!$.;KZflkcWH;/'!".=M\g4/07BO[dgd\PD;67>JXfqwvpeYMB92,'#!*6DS_fgbXL@5-'"#.=M[e1--3>JV^a]UJ?6117AN\gnokcYOE<4.("$/IRVVQKC;3-'")5BNU%!"'/9BHJGA8/'"!$+5@JRVWTNG?70)"'271+% #-9BI%-5:;94,% (1:AFGFB=70)" &.6;==:61,&!%.5:"(+-+'!#+157751,&  "(,/0.,($ "(,  "%'(&$   "#"                        O51/  .  +  # $)*(# ! %-231+" !  *39;81' !  "-6=>;4* !  #-6<>:3)   !*3896/%  "'*+($'.23/)  '/6996/'%*-,)#    +6?FJIC;1'!%)*($    8DOWZWPF:.%"&*++("   "$DR^fhd[OA5+&%&*/220+$  !"$%&&%!"'*,+)'%$%(,03O^jqrmbTF91,,05:==81(!$&'()+-0221.)#!'.5:<;952126;@CWfrxwpdUG;4139@FIHB9.##(,/00/0259;6/)&'+2;DJLKHC?=>CIOS]kv{xpbSE;549AJRUSLA4("(/47886446:?EIKHB;4004=GQY\ZVPKHINT[``mwzvk]NA746=HS[_\TG9-$ !&-4;@BA=965798=FR]ehfaYSPPU\dj`muvpdUF:316@MYbebXK=1)')08AGJJF@:5363./6BP]gje[M?4.-2;DLQROH?7102:FR^efaXNGFJTamuwtlbZTTYajr_jnkaSD6-*-6DSajkf[M@635N^inlcWKB?CN[hprk^M<.$!#*6CQ[aa]WPNPWajppj^PC;8BLXdllfZK<0)'+2GS^fgbWJ=3-+/5=DIKIE@<;?GR\bc^SF90-1:HWcklhd[M?3,)-7ET`hidZMA969ALW^`]TI>50/16<@CB>95239BMV\[UJ=2*).8FUahha]TH;0)'+4AOZab]SG<4029BLTWUOF=620258::73.*),25,%!!%,4:?@>:61.,++*(&"#+39;93+"(3>FKK<93+#'07;;81*"!'-1331.+(&$#!"(-.,'  )29<<-+& $),,*%!$''&%"  !"  %+--                   ,,,         $"  30+$ #&((''&%#  D@90&#*/344310.,(# TPH=0%%.6=@A@=:863.)! b]TG9,"$.9CJMMJEA>;72,$ lg]O@1'"$+6BNVYXSMFA=93-% rncTD5*%'0- g^PB4*# !$+6BQ`muvqfUC1! g]PB6-'%%'+3=JXfptqgXF4# g]PC91-+*+.2:ER_jpogYG5% g]QE<63211249AMYdjkdWF4$ f\QG?:9887679@IS]cd^RB2" cZOF@<<;:9:>ENV[[UJ<- ]TKC=;;=>=<;;=BHNQPK@4' SLC=878:;;:98:=AEFD?6+  GA:400135654468::82+! 94.)'&(*,--,--./.+&  +'" "#$$##$$"          uq8  Text Layer      22"@r@~2>6C:A>8qU8Uq8q8q q UU88UU8qUqUUUqUUUqUUq8U8 UU 8q8U8 q   8U 8U UU UU UU 8UU U 8 88 U q 8888 q8 q8qUUUUUqU UUUU U 8qUq q8UqUU8qU 8q8U8 8UqU8qqq88qqUUqUUUqƪUqUUUU8Uqq q8UUU 88UUqq UUUU UUUU UUUU UUUU UUUU UUUU UUUU UUUU UUUU UUUU UUUU UUUU UUUU UUUU UUUU qUq qUqU8qU88qU8UƍUUUU8q qq q8  8qUU88qU 88 8UU UUUU8U8UUUUUUUUU8q 8UqUUU UUUUU 8UUUU UUUUU UUUU UUUU UUUUUU UUUUUU UUUUU UUUUUU UUUUU8 UUUU qUUUUq UUUUq8UUUUUUUUqUqU88UUqqU8q8qUU 8Uq8 q 8VVV UU ⪪88888Uqqq88  q 8 qU  qU qq8qƪq888UUk 5$ Drop-ShadowD       A2$AN^e^q$AjIpQZ   L          &.49<=<80% &-38<>=:4," & +7BJOTX\_^WI7%   -:CJOSWZ]]ZQE5% #1@L &8HTZ\\]bkwu_D*  )beD( ;eQ*=e]9 &BhoD$*Ky0V}zT0 )LtrI'.TwK'*Mzȳ\3 >m BmoD"  3QlxoV7 >ji<  8dŢrC  6f+Sd8 0BJE5"'M~_2)QϴR) 3c5b\0  $" /[ȷX, CuԿ^1 2b ?oX,   6e̸V*8iƝh8 2b !GxW+ ;lѺW+1_ʣn<2b $L¶Z- >pԾZ-,Yʤp>2b%NǼa3 >o×a2*UȢn<2b %Mßl<  ;kɠj:)TÝh8 2b "I|ʬ}K& 6cΪvD +Vʼ_1 2b Bsѻa7  0YҴP(.[ıS) 2b8gɨ{O-  !,/*)K|Ӿ`35cuE! 2b-WӾpJ. )7@?2" =iŢrC!  @n`6 2b !EtϷpQ;-%#%,7EPQF2-SȰX1 *NzuJ&3c3[ͷgVLHJQZabXC+ m*Krƻs[@' -Lo|aI:35>Ocu|t]@% )Jw .MpĽw^C*  -IgveWPPV_hleT<% !8X~ -Gd~oX?)  )?Vjvyume`]][SF4!  )A\z &:Napz~|uiYG4"   1AOY]][WSNH@5( (<82+# +7AIM !##      !$&     ?   @         !! )   ! )&(4>DE@6(  ,8AFFA6) !(*% ,8AFD=2# PI:+%*8HYgqtoaM6#,=N^ksuoaM5  (6EOOE4'%-mѽ`4  #5YʰW2 3Yʹ]6ĶnI, 6V~ƺuO1 6U}ĶpL2%$.Deb?&&AdıhEmO5!(>ZysU:&)>ZxnR<0/9LgcF-.GeiLzm[F1!'9Nbs~|q_K7&'9Nbs}zm[I90/7EWiw~vgT?,,@ViwykXDNLF<1$)5@HMOMG?4')5@HMNLF=3*%$)1;DJNNJC9-  -:DJNNKE;0&%# !$&&$  !$&&%# #%&&%" "%&&%#         >   A      "       "$0;CGE>2#  #+17;=><7/&  $+.+"%1$ .Hfmceo|acgn{a6 %A`y}kTA516CXra?$1MpʸnfejtOHEHTlwG"  <`yZ='&9Uw^9)DiãfTJHN_z6)$&1JpdzU+ 1WjD' 7Z~R.4ZuR:,'+;Y 3Zȼa3 #FrY1 !@kɽk? (M~Һb<#"@l&Lžj:1ZyJ$,T˰Q*"ExͱR+  1^  Fxţp??mo?  Bsҿb5 CuɫzH" +W  CvƦsA &K}i85cɣp? CuȨvD )T  BuƦtB",UÜf6,WέzG$!CuǧuB (R  BuǧtC#0[ƞg6&NвL'!CuǧuB (R  BuǧtC#2^ʢl: "H|гN("CuǧuB (R  BuǧuC#1^ͨs@  ExαL'!CuǧuB (R  BuǧuC#/YѰ}I"  DwʬzH$!CuǧuB (R  BuǧuC"*RԸS) FyĢp@ CuǧuB (R  BuǧuC!$Hza3 $K~ûc6 BuǧuB (R  BuǧuB 43:H\p|yfJ-  1X˰X3 "@k*'@cb@& &@]x{j[QOS\eki[E- "=b­c@'/Nu3!/GddG. "7Odsywpha^]]\WK:(  (CcdG/#7Sr0!-@Uhw~~vhU@-+=94.& *7CJNNJC:.!%2>G "%&&%"    "%&&%"  $      ?       -  &-13321/,)! U>' )8BGHHJKNNI<) eE( 1FUZWRNMRZeljX< ĩf?  0LdmgXI@?GVj{~kI'W/&Fh}|hL6)'0B\upN*ɾm> 4[d@%+EaqhK)ȭ~K$ ?kf=  /I[XB%̷U* !EtsI( 3CE5 ̽\. Etc@'".0& `0 >leH1!a12\sXA.!b2%GrµlS=+ b2 0S{fL5" ̶b2 5UxȽx[?' b24PnŸeD(b2 .D^zf@"b2 %7MgĬ[3b2 )-$$,=XupM+ƾ}U4$@b|yeQB;;BPbquiP3 xX;$3Mcli_TLHINV^`YH2|}sbL5""3AHIGDCCEHJJD9*MOMH@4&"&()+-/121.' &$!     )p8 ,d Background     _$,d_D__`,d_x_________               0002K% collections-generic-4.01/src/test/0000755000175000017500000000000010464140754017347 5ustar giovannigiovannicollections-generic-4.01/src/test/org/0000755000175000017500000000000010464140754020136 5ustar giovannigiovannicollections-generic-4.01/src/test/org/apache/0000755000175000017500000000000010464140754021357 5ustar giovannigiovannicollections-generic-4.01/src/test/org/apache/commons/0000755000175000017500000000000010464140754023032 5ustar giovannigiovannicollections-generic-4.01/src/test/org/apache/commons/collections15/0000755000175000017500000000000011664401370025513 5ustar giovannigiovannicollections-generic-4.01/src/test/org/apache/commons/collections15/TestAllPackages.java0000644000175000017500000000426210464140765031376 0ustar giovannigiovanni/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * Entry point for all Collections project tests. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:39 $ */ public class TestAllPackages extends TestCase { public TestAllPackages(String testName) { super(testName); } public static Test suite() { TestSuite suite = new TestSuite(); suite.addTest(org.apache.commons.collections15.TestAll.suite()); suite.addTest(org.apache.commons.collections15.bag.TestAll.suite()); suite.addTest(org.apache.commons.collections15.bidimap.TestAll.suite()); suite.addTest(org.apache.commons.collections15.buffer.TestAll.suite()); suite.addTest(org.apache.commons.collections15.collection.TestAll.suite()); suite.addTest(org.apache.commons.collections15.comparators.TestAll.suite()); suite.addTest(org.apache.commons.collections15.iterators.TestAll.suite()); suite.addTest(org.apache.commons.collections15.keyvalue.TestAll.suite()); suite.addTest(org.apache.commons.collections15.list.TestAll.suite()); suite.addTest(org.apache.commons.collections15.map.TestAll.suite()); suite.addTest(org.apache.commons.collections15.set.TestAll.suite()); return suite; } public static void main(String args[]) { String[] testCaseName = {TestAllPackages.class.getName()}; junit.textui.TestRunner.main(testCaseName); } } collections-generic-4.01/src/test/org/apache/commons/collections15/buffer/0000755000175000017500000000000011664401370026764 5ustar giovannigiovanni././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootcollections-generic-4.01/src/test/org/apache/commons/collections15/buffer/TestBoundedFifoBuffer2.javacollections-generic-4.01/src/test/org/apache/commons/collections15/buffer/TestBoundedFifoBuffer2.jav0000644000175000017500000000714710464140755033743 0ustar giovannigiovanni/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.buffer; import junit.framework.Test; import org.apache.commons.collections15.BoundedCollection; import org.apache.commons.collections15.BufferOverflowException; import org.apache.commons.collections15.BulkTest; import java.util.Arrays; import java.util.Collection; /** * Runs tests against a full BoundedFifoBuffer, since many of the algorithms * differ depending on whether the fifo is full or not. * * @author Matt Hall, John Watkinson, Unknown * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:44 $ */ public class TestBoundedFifoBuffer2 extends TestBoundedFifoBuffer { public TestBoundedFifoBuffer2(String n) { super(n); } public static Test suite() { return BulkTest.makeSuite(TestBoundedFifoBuffer2.class); } /** * Returns a BoundedFifoBuffer that's filled to capacity. * Any attempt to add to the returned buffer will result in a * BufferOverflowException. * * @return a full BoundedFifoBuffer */ public Collection makeFullCollection() { return new BoundedFifoBuffer(Arrays.asList(getFullElements())); } /** * Overridden to skip the add tests. All of them would fail with a * BufferOverflowException. * * @return false */ public boolean isAddSupported() { return false; } /** * Overridden because the add operations raise BufferOverflowException * instead of UnsupportedOperationException. */ public void testUnsupportedAdd() { } /** * Tests to make sure the add operations raise BufferOverflowException. */ public void testBufferOverflow() { resetFull(); try { collection.add(getOtherElements()[0]); fail("add should raise BufferOverflow."); } catch (BufferOverflowException e) { // expected } verify(); try { collection.addAll(Arrays.asList(getOtherElements())); fail("addAll should raise BufferOverflow."); } catch (BufferOverflowException e) { // expected } verify(); } /** * Tests is full */ public void testIsFull() { resetFull(); assertEquals(true, ((BoundedCollection) collection).isFull()); ((BoundedFifoBuffer) collection).remove(); assertEquals(false, ((BoundedCollection) collection).isFull()); ((BoundedFifoBuffer) collection).add("jj"); assertEquals(true, ((BoundedCollection) collection).isFull()); } /** * Tests max size */ public void testMaxSize() { resetFull(); assertEquals(getFullElements().length, ((BoundedCollection) collection).maxSize()); ((BoundedFifoBuffer) collection).remove(); assertEquals(getFullElements().length, ((BoundedCollection) collection).maxSize()); ((BoundedFifoBuffer) collection).add("jj"); assertEquals(getFullElements().length, ((BoundedCollection) collection).maxSize()); } } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootcollections-generic-4.01/src/test/org/apache/commons/collections15/buffer/TestCircularFifoBuffer.javacollections-generic-4.01/src/test/org/apache/commons/collections15/buffer/TestCircularFifoBuffer.jav0000644000175000017500000001413310464140761034033 0ustar giovannigiovanni/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.buffer; import junit.framework.Test; import org.apache.commons.collections15.Buffer; import org.apache.commons.collections15.BufferUnderflowException; import org.apache.commons.collections15.BulkTest; import org.apache.commons.collections15.collection.AbstractTestCollection; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; /** * Test cases for CircularFifoBuffer. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:44 $ */ public class TestCircularFifoBuffer extends AbstractTestCollection { public TestCircularFifoBuffer(String n) { super(n); } public static Test suite() { return BulkTest.makeSuite(TestCircularFifoBuffer.class); } //----------------------------------------------------------------------- /** * Runs through the regular verifications, but also verifies that * the buffer contains the same elements in the same sequence as the * list. */ public void verify() { super.verify(); Iterator iterator1 = collection.iterator(); Iterator iterator2 = confirmed.iterator(); while (iterator2.hasNext()) { assertTrue(iterator1.hasNext()); Object o1 = iterator1.next(); Object o2 = iterator2.next(); assertEquals(o1, o2); } } //----------------------------------------------------------------------- /** * Overridden because UnboundedFifoBuffer doesn't allow null elements. * * @return false */ public boolean isNullSupported() { return false; } /** * Overridden because UnboundedFifoBuffer isn't fail fast. * * @return false */ public boolean isFailFastSupported() { return false; } //----------------------------------------------------------------------- /** * Returns an empty ArrayList. * * @return an empty ArrayList */ public Collection makeConfirmedCollection() { return new ArrayList(); } /** * Returns a full ArrayList. * * @return a full ArrayList */ public Collection makeConfirmedFullCollection() { Collection c = makeConfirmedCollection(); c.addAll(java.util.Arrays.asList(getFullElements())); return c; } /** * Returns an empty BoundedFifoBuffer that won't overflow. * * @return an empty BoundedFifoBuffer */ public Collection makeCollection() { return new CircularFifoBuffer(100); } //----------------------------------------------------------------------- /** * Tests that the removal operation actually removes the first element. */ public void testCircularFifoBufferCircular() { List list = new ArrayList(); list.add("A"); list.add("B"); list.add("C"); Buffer buf = new CircularFifoBuffer(list); assertEquals(true, buf.contains("A")); assertEquals(true, buf.contains("B")); assertEquals(true, buf.contains("C")); buf.add("D"); assertEquals(false, buf.contains("A")); assertEquals(true, buf.contains("B")); assertEquals(true, buf.contains("C")); assertEquals(true, buf.contains("D")); assertEquals("B", buf.get()); assertEquals("B", buf.remove()); assertEquals("C", buf.remove()); assertEquals("D", buf.remove()); } /** * Tests that the removal operation actually removes the first element. */ public void testCircularFifoBufferRemove() { resetFull(); int size = confirmed.size(); for (int i = 0; i < size; i++) { Object o1 = ((CircularFifoBuffer) collection).remove(); Object o2 = ((ArrayList) confirmed).remove(0); assertEquals("Removed objects should be equal", o1, o2); verify(); } try { ((CircularFifoBuffer) collection).remove(); fail("Empty buffer should raise Underflow."); } catch (BufferUnderflowException e) { // expected } } /** * Tests that the constructor correctly throws an exception. */ public void testConstructorException1() { try { new CircularFifoBuffer(0); } catch (IllegalArgumentException ex) { return; } fail(); } /** * Tests that the constructor correctly throws an exception. */ public void testConstructorException2() { try { new CircularFifoBuffer(-20); } catch (IllegalArgumentException ex) { return; } fail(); } /** * Tests that the constructor correctly throws an exception. */ public void testConstructorException3() { try { new CircularFifoBuffer(null); } catch (NullPointerException ex) { return; } fail(); } public String getCompatibilityVersion() { return "3.1"; } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk((java.io.Serializable) collection, "D:/dev/collections15/data/test/CircularFifoBuffer.emptyCollection.version3.1.obj"); // resetFull(); // writeExternalFormToDisk((java.io.Serializable) collection, "D:/dev/collections15/data/test/CircularFifoBuffer.fullCollection.version3.1.obj"); // } } collections-generic-4.01/src/test/org/apache/commons/collections15/buffer/TestTransformedBuffer.java0000644000175000017500000000441610464140765034117 0ustar giovannigiovanni/* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.buffer; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.apache.commons.collections15.ArrayStack; import org.apache.commons.collections15.Buffer; import org.apache.commons.collections15.collection.TestTransformedCollection; /** * Extension of {@link TestBuffer} for exercising the {@link TransformedBuffer} * implementation. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:44 $ * @since Commons Collections 3.0 */ public class TestTransformedBuffer extends TestCase { public TestTransformedBuffer(String testName) { super(testName); } public static Test suite() { return new TestSuite(TestTransformedBuffer.class); } public static void main(String args[]) { String[] testCaseName = {TestTransformedBuffer.class.getName()}; junit.textui.TestRunner.main(testCaseName); } public void testTransformedBuffer() { Buffer buffer = TransformedBuffer.decorate(new ArrayStack(), TestTransformedCollection.STRING_TO_INTEGER_TRANSFORMER); assertEquals(0, buffer.size()); Object[] els = new Object[]{"1", "3", "5", "7", "2", "4", "6"}; for (int i = 0; i < els.length; i++) { buffer.add(els[i]); assertEquals(i + 1, buffer.size()); assertEquals(true, buffer.contains(new Integer((String) els[i]))); assertEquals(false, buffer.contains(els[i])); } assertEquals(false, buffer.remove(els[0])); assertEquals(true, buffer.remove(new Integer((String) els[0]))); } } collections-generic-4.01/src/test/org/apache/commons/collections15/buffer/TestBlockingBuffer.java0000644000175000017500000004041710464140757033365 0ustar giovannigiovanni/* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.buffer; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.collections15.AbstractTestObject; import org.apache.commons.collections15.Buffer; import org.apache.commons.collections15.BufferUnderflowException; import java.util.*; /** * Extension of {@link TestObject} for exercising the {@link BlockingBuffer} * implementation. * * @author Janek Bogucki * @author Matt Hall, John Watkinson, Phil Steitz * @version $Revision: 1.1 $ * @since Commons Collections 3.0 */ public class TestBlockingBuffer extends AbstractTestObject { public TestBlockingBuffer(String testName) { super(testName); } public static Test suite() { return new TestSuite(TestBlockingBuffer.class); } public static void main(String args[]) { String[] testCaseName = {TestBlockingBuffer.class.getName()}; junit.textui.TestRunner.main(testCaseName); } public Object makeObject() { return BlockingBuffer.decorate(new MyBuffer()); } public boolean isEqualsCheckable() { return false; } //----------------------------------------------------------------------- /** * Tests {@link BlockingBuffer#get()} in combination with {@link BlockingBuffer#add()}. */ public void testGetWithAdd() { Buffer blockingBuffer = BlockingBuffer.decorate(new MyBuffer()); Object obj = new Object(); new DelayedAdd(blockingBuffer, obj).start(); // verify does not throw BufferUnderflowException; should block until other thread has added to the buffer . assertSame(obj, blockingBuffer.get()); } //----------------------------------------------------------------------- /** * Tests {@link BlockingBuffer#get()} in combination with {@link BlockingBuffer#addAll()}. */ public void testGetWithAddAll() { Buffer blockingBuffer = BlockingBuffer.decorate(new MyBuffer()); Object obj = new Object(); new DelayedAddAll(blockingBuffer, obj).start(); // verify does not throw BufferUnderflowException; should block until other thread has added to the buffer . assertSame(obj, blockingBuffer.get()); } //----------------------------------------------------------------------- /** * Tests {@link BlockingBuffer#remove()} in combination with {@link BlockingBuffer#add()}. */ public void testRemoveWithAdd() { Buffer blockingBuffer = BlockingBuffer.decorate(new MyBuffer()); Object obj = new Object(); new DelayedAdd(blockingBuffer, obj).start(); // verify does not throw BufferUnderflowException; should block until other thread has added to the buffer . assertSame(obj, blockingBuffer.remove()); } //----------------------------------------------------------------------- /** * Tests {@link BlockingBuffer#remove()} in combination with {@link BlockingBuffer#addAll()}. */ public void testRemoveWithAddAll() { Buffer blockingBuffer = BlockingBuffer.decorate(new MyBuffer()); Object obj = new Object(); new DelayedAddAll(blockingBuffer, obj).start(); // verify does not throw BufferUnderflowException; should block until other thread has added to the buffer . assertSame(obj, blockingBuffer.remove()); } //----------------------------------------------------------------------- /** * Tests {@link BlockingBuffer#get()} in combination with {@link BlockingBuffer#add()} using multiple read threads. *

                  * Two read threads should block on an empty buffer until one object * is added then both threads should complete. */ public void testBlockedGetWithAdd() { Buffer blockingBuffer = BlockingBuffer.decorate(new MyBuffer()); Object obj = new Object(); // run methods will get and compare -- must wait for add Thread thread1 = new ReadThread(blockingBuffer, obj); Thread thread2 = new ReadThread(blockingBuffer, obj); thread1.start(); thread2.start(); // give hungry read threads ample time to hang delay(); // notifyAll should allow both read threads to complete blockingBuffer.add(obj); // allow notified threads to complete delay(); // There should not be any threads waiting. if (thread1.isAlive() || thread2.isAlive()) fail("Live thread(s) when both should be dead."); } //----------------------------------------------------------------------- /** * Tests {@link BlockingBuffer#get()} in combination with {@link BlockingBuffer#addAll()} using multiple read threads. *

                  * Two read threads should block on an empty buffer until a * singleton is added then both threads should complete. */ public void testBlockedGetWithAddAll() { Buffer blockingBuffer = BlockingBuffer.decorate(new MyBuffer()); Object obj = new Object(); // run methods will get and compare -- must wait for addAll Thread thread1 = new ReadThread(blockingBuffer, obj); Thread thread2 = new ReadThread(blockingBuffer, obj); thread1.start(); thread2.start(); // give hungry read threads ample time to hang delay(); // notifyAll should allow both read threads to complete blockingBuffer.addAll(Collections.singleton(obj)); // allow notified threads to complete delay(); // There should not be any threads waiting. if (thread1.isAlive() || thread2.isAlive()) fail("Live thread(s) when both should be dead."); } //----------------------------------------------------------------------- /** * Tests interrupted {@link BlockingBuffer#get()}. */ public void testInterruptedGet() { Buffer blockingBuffer = BlockingBuffer.decorate(new MyBuffer()); Object obj = new Object(); // spawn a read thread to wait on the empty buffer ArrayList exceptionList = new ArrayList(); Thread thread = new ReadThread(blockingBuffer, obj, exceptionList); thread.start(); // Interrupting the thread should cause it to throw BufferUnderflowException thread.interrupt(); // Chill, so thread can throw and add message to exceptionList delay(); assertTrue("Thread interrupt should have led to underflow", exceptionList.contains("BufferUnderFlow")); if (thread.isAlive()) { fail("Read thread has hung."); } } //----------------------------------------------------------------------- /** * Tests {@link BlockingBuffer#remove()} in combination with {@link BlockingBuffer#add()} using multiple read threads. *

                  * Two read threads should block on an empty buffer until one * object is added then one thread should complete. The remaining * thread should complete after the addition of a second object. */ public void testBlockedRemoveWithAdd() { Buffer blockingBuffer = BlockingBuffer.decorate(new MyBuffer()); Object obj = new Object(); // run methods will remove and compare -- must wait for add Thread thread1 = new ReadThread(blockingBuffer, obj, null, "remove"); Thread thread2 = new ReadThread(blockingBuffer, obj, null, "remove"); thread1.start(); thread2.start(); // give hungry read threads ample time to hang delay(); blockingBuffer.add(obj); // allow notified threads to complete delay(); // There should be one thread waiting. assertTrue("There is one thread waiting", thread1.isAlive() ^ thread2.isAlive()); blockingBuffer.add(obj); // allow notified thread to complete delay(); // There should not be any threads waiting. if (thread1.isAlive() || thread2.isAlive()) fail("Live thread(s) when both should be dead."); } //----------------------------------------------------------------------- /** * Tests {@link BlockingBuffer#remove()} in combination with {@link BlockingBuffer#addAll()} using multiple read threads. *

                  * Two read threads should block on an empty buffer until a * singleton collection is added then one thread should * complete. The remaining thread should complete after the * addition of a second singleton. */ public void testBlockedRemoveWithAddAll1() { Buffer blockingBuffer = BlockingBuffer.decorate(new MyBuffer()); Object obj = new Object(); // run methods will remove and compare -- must wait for addAll Thread thread1 = new ReadThread(blockingBuffer, obj, null, "remove"); Thread thread2 = new ReadThread(blockingBuffer, obj, null, "remove"); thread1.start(); thread2.start(); // give hungry read threads ample time to hang delay(); blockingBuffer.addAll(Collections.singleton(obj)); // allow notified threads to complete delay(); // There should be one thread waiting. assertTrue("There is one thread waiting", thread1.isAlive() ^ thread2.isAlive()); blockingBuffer.addAll(Collections.singleton(obj)); // allow notified thread to complete delay(); // There should not be any threads waiting. if (thread1.isAlive() || thread2.isAlive()) fail("Live thread(s) when both should be dead."); } //----------------------------------------------------------------------- /** * Tests {@link BlockingBuffer#remove()} in combination with {@link BlockingBuffer#addAll()} using multiple read threads. *

                  * Two read threads should block on an empty buffer until a * collection with two distinct objects is added then both * threads should complete. Each thread should have read a * different object. */ public void testBlockedRemoveWithAddAll2() { Buffer blockingBuffer = BlockingBuffer.decorate(new MyBuffer()); Object obj1 = new Object(); Object obj2 = new Object(); Set objs = Collections.synchronizedSet(new HashSet()); objs.add(obj1); objs.add(obj2); // run methods will remove and compare -- must wait for addAll Thread thread1 = new ReadThread(blockingBuffer, objs, "remove"); Thread thread2 = new ReadThread(blockingBuffer, objs, "remove"); thread1.start(); thread2.start(); // give hungry read threads ample time to hang delay(); blockingBuffer.addAll(objs); // allow notified threads to complete delay(); assertEquals("Both objects were removed", 0, objs.size()); // There should not be any threads waiting. if (thread1.isAlive() || thread2.isAlive()) fail("Live thread(s) when both should be dead."); } //----------------------------------------------------------------------- /** * Tests interrupted remove. */ public void testInterruptedRemove() { Buffer blockingBuffer = BlockingBuffer.decorate(new MyBuffer()); Object obj = new Object(); // spawn a read thread to wait on the empty buffer ArrayList exceptionList = new ArrayList(); Thread thread = new ReadThread(blockingBuffer, obj, exceptionList, "remove"); thread.start(); // Interrupting the thread should cause it to throw BufferUnderflowException thread.interrupt(); // Chill, so thread can throw and add message to exceptionList delay(); assertTrue("Thread interrupt should have led to underflow", exceptionList.contains("BufferUnderFlow")); if (thread.isAlive()) { fail("Read thread has hung."); } } protected static class DelayedAdd extends Thread { Buffer buffer; Object obj; DelayedAdd(Buffer buffer, Object obj) { super(); this.buffer = buffer; this.obj = obj; } public void run() { try { // wait for other thread to block on get() or remove() Thread.currentThread().sleep(100); } catch (InterruptedException e) { } buffer.add(obj); } } protected static class DelayedAddAll extends Thread { Buffer buffer; Object obj; DelayedAddAll(Buffer buffer, Object obj) { super(); this.buffer = buffer; this.obj = obj; } public void run() { try { // wait for other thread to block on get() or remove() Thread.currentThread().sleep(100); } catch (InterruptedException e) { } buffer.addAll(Collections.singleton(obj)); } } protected static class ReadThread extends Thread { Buffer buffer; Object obj; ArrayList exceptionList = null; String action = "get"; Set objs; ReadThread(Buffer buffer, Object obj) { super(); this.buffer = buffer; this.obj = obj; } ReadThread(Buffer buffer, Object obj, ArrayList exceptionList) { super(); this.buffer = buffer; this.obj = obj; this.exceptionList = exceptionList; } ReadThread(Buffer buffer, Object obj, ArrayList exceptionList, String action) { super(); this.buffer = buffer; this.obj = obj; this.exceptionList = exceptionList; this.action = action; } ReadThread(Buffer buffer, Set objs, String action) { super(); this.buffer = buffer; this.objs = objs; this.action = action; } public void run() { try { if (action == "get") { assertSame(obj, buffer.get()); } else { if (null != obj) assertSame(obj, buffer.remove()); else assertTrue(objs.remove(buffer.remove())); } } catch (BufferUnderflowException ex) { exceptionList.add("BufferUnderFlow"); } } } protected static class MyBuffer extends LinkedList implements Buffer { public Object get() { if (isEmpty()) throw new BufferUnderflowException(); return get(0); } public Object remove() { if (isEmpty()) throw new BufferUnderflowException(); return remove(0); } } private void delay() { try { Thread.currentThread().sleep(100); } catch (InterruptedException e) { } } public String getCompatibilityVersion() { return "3.1"; } // public void testCreate() throws Exception { // Buffer buffer = BlockingBuffer.decorate(new UnboundedFifoBuffer()); // writeExternalFormToDisk((java.io.Serializable) buffer, "D:/dev/collections15/data/test/BlockingBuffer.emptyCollection.version3.1.obj"); // buffer = BlockingBuffer.decorate(new UnboundedFifoBuffer()); // buffer.add("A"); // buffer.add("B"); // buffer.add("C"); // writeExternalFormToDisk((java.io.Serializable) buffer, "D:/dev/collections15/data/test/BlockingBuffer.fullCollection.version3.1.obj"); // } } collections-generic-4.01/src/test/org/apache/commons/collections15/buffer/TestBoundedFifoBuffer.java0000644000175000017500000001231210464140755034010 0ustar giovannigiovanni/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.buffer; import junit.framework.Test; import org.apache.commons.collections15.BufferUnderflowException; import org.apache.commons.collections15.BulkTest; import org.apache.commons.collections15.collection.AbstractTestCollection; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; /** * Test cases for BoundedFifoBuffer. * * @author Matt Hall, John Watkinson, Paul Jack * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:44 $ */ public class TestBoundedFifoBuffer extends AbstractTestCollection { public TestBoundedFifoBuffer(String n) { super(n); } public static Test suite() { return BulkTest.makeSuite(TestBoundedFifoBuffer.class); } //----------------------------------------------------------------------- /** * Runs through the regular verifications, but also verifies that * the buffer contains the same elements in the same sequence as the * list. */ public void verify() { super.verify(); Iterator iterator1 = collection.iterator(); Iterator iterator2 = confirmed.iterator(); while (iterator2.hasNext()) { assertTrue(iterator1.hasNext()); Object o1 = iterator1.next(); Object o2 = iterator2.next(); assertEquals(o1, o2); } } //----------------------------------------------------------------------- /** * Overridden because UnboundedFifoBuffer doesn't allow null elements. * * @return false */ public boolean isNullSupported() { return false; } /** * Overridden because UnboundedFifoBuffer isn't fail fast. * * @return false */ public boolean isFailFastSupported() { return false; } //----------------------------------------------------------------------- /** * Returns an empty ArrayList. * * @return an empty ArrayList */ public Collection makeConfirmedCollection() { return new ArrayList(); } /** * Returns a full ArrayList. * * @return a full ArrayList */ public Collection makeConfirmedFullCollection() { Collection c = makeConfirmedCollection(); c.addAll(java.util.Arrays.asList(getFullElements())); return c; } /** * Returns an empty BoundedFifoBuffer that won't overflow. * * @return an empty BoundedFifoBuffer */ public Collection makeCollection() { return new BoundedFifoBuffer(100); } //----------------------------------------------------------------------- /** * Tests that the removal operation actually removes the first element. */ public void testBoundedFifoBufferRemove() { resetFull(); int size = confirmed.size(); for (int i = 0; i < size; i++) { Object o1 = ((BoundedFifoBuffer) collection).remove(); Object o2 = ((ArrayList) confirmed).remove(0); assertEquals("Removed objects should be equal", o1, o2); verify(); } try { ((BoundedFifoBuffer) collection).remove(); fail("Empty buffer should raise Underflow."); } catch (BufferUnderflowException e) { // expected } } /** * Tests that the constructor correctly throws an exception. */ public void testConstructorException1() { try { new BoundedFifoBuffer(0); } catch (IllegalArgumentException ex) { return; } fail(); } /** * Tests that the constructor correctly throws an exception. */ public void testConstructorException2() { try { new BoundedFifoBuffer(-20); } catch (IllegalArgumentException ex) { return; } fail(); } /** * Tests that the constructor correctly throws an exception. */ public void testConstructorException3() { try { new BoundedFifoBuffer(null); } catch (NullPointerException ex) { return; } fail(); } public String getCompatibilityVersion() { return "3.1"; } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk((java.io.Serializable) collection, "D:/dev/collections15/data/test/BoundedFifoBuffer.emptyCollection.version3.1.obj"); // resetFull(); // writeExternalFormToDisk((java.io.Serializable) collection, "D:/dev/collections15/data/test/BoundedFifoBuffer.fullCollection.version3.1.obj"); // } } collections-generic-4.01/src/test/org/apache/commons/collections15/buffer/TestPriorityBuffer.java0000644000175000017500000002534410464140762033454 0ustar giovannigiovanni/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.buffer; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.collections15.Buffer; import org.apache.commons.collections15.BufferUnderflowException; import org.apache.commons.collections15.ComparatorUtils; import org.apache.commons.collections15.collection.AbstractTestCollection; import org.apache.commons.collections15.comparators.ComparableComparator; import org.apache.commons.collections15.comparators.ReverseComparator; import java.util.*; /** * Tests the PriorityBuffer. * * @author Matt Hall, John Watkinson, Michael A. Smith * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:44 $ */ public class TestPriorityBuffer extends AbstractTestCollection { public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static Test suite() { return new TestSuite(TestPriorityBuffer.class); } public TestPriorityBuffer(String testName) { super(testName); } //----------------------------------------------------------------------- public void verify() { super.verify(); PriorityBuffer heap = (PriorityBuffer) collection; Comparator c = heap.comparator; if (c == null) { c = ComparatorUtils.naturalComparator(); } if (!heap.ascendingOrder) { c = ComparatorUtils.reversedComparator(c); } Object[] tree = heap.elements; for (int i = 1; i <= heap.size; i++) { Object parent = tree[i]; if (i * 2 <= heap.size) { assertTrue("Parent is less than or equal to its left child", c.compare(parent, tree[i * 2]) <= 0); } if (i * 2 + 1 < heap.size) { assertTrue("Parent is less than or equal to its right child", c.compare(parent, tree[i * 2 + 1]) <= 0); } } } //----------------------------------------------------------------------- /** * Overridden because BinaryBuffer isn't fail fast. * * @return false */ public boolean isFailFastSupported() { return false; } //----------------------------------------------------------------------- public Collection makeConfirmedCollection() { return new ArrayList(); } public Collection makeConfirmedFullCollection() { ArrayList list = new ArrayList(); list.addAll(Arrays.asList(getFullElements())); return list; } /** * Return a new, empty {@link Object} to used for testing. */ public Collection makeCollection() { return new PriorityBuffer(); } //----------------------------------------------------------------------- public Object[] getFullElements() { return getFullNonNullStringElements(); } public Object[] getOtherElements() { return getOtherNonNullStringElements(); } //----------------------------------------------------------------------- public void testBufferEmpty() { resetEmpty(); Buffer buffer = (Buffer) collection; assertEquals(0, buffer.size()); assertEquals(true, buffer.isEmpty()); try { buffer.get(); fail(); } catch (BufferUnderflowException ex) { } try { buffer.remove(); fail(); } catch (BufferUnderflowException ex) { } } public void testBasicOps() { PriorityBuffer heap = new PriorityBuffer(); heap.add("a"); heap.add("c"); heap.add("e"); heap.add("b"); heap.add("d"); heap.add("n"); heap.add("m"); heap.add("l"); heap.add("k"); heap.add("j"); heap.add("i"); heap.add("h"); heap.add("g"); heap.add("f"); assertTrue("heap should not be empty after adds", !heap.isEmpty()); for (int i = 0; i < 14; i++) { assertEquals("get using default constructor should return minimum value in the binary heap", String.valueOf((char) ('a' + i)), heap.get()); assertEquals("remove using default constructor should return minimum value in the binary heap", String.valueOf((char) ('a' + i)), heap.remove()); if (i + 1 < 14) { assertTrue("heap should not be empty before all elements are removed", !heap.isEmpty()); } else { assertTrue("heap should be empty after all elements are removed", heap.isEmpty()); } } try { heap.get(); fail("NoSuchElementException should be thrown if get is called after all elements are removed"); } catch (BufferUnderflowException ex) { } try { heap.remove(); fail("NoSuchElementException should be thrown if remove is called after all elements are removed"); } catch (BufferUnderflowException ex) { } } public void testBasicComparatorOps() { PriorityBuffer heap = new PriorityBuffer(new ReverseComparator(new ComparableComparator())); assertTrue("heap should be empty after create", heap.isEmpty()); try { heap.get(); fail("NoSuchElementException should be thrown if get is called before any elements are added"); } catch (BufferUnderflowException ex) { } try { heap.remove(); fail("NoSuchElementException should be thrown if remove is called before any elements are added"); } catch (BufferUnderflowException ex) { } heap.add("a"); heap.add("c"); heap.add("e"); heap.add("b"); heap.add("d"); heap.add("n"); heap.add("m"); heap.add("l"); heap.add("k"); heap.add("j"); heap.add("i"); heap.add("h"); heap.add("g"); heap.add("f"); assertTrue("heap should not be empty after adds", !heap.isEmpty()); for (int i = 0; i < 14; i++) { // note: since we're using a comparator that reverses items, the // "minimum" item is "n", and the "maximum" item is "a". assertEquals("get using default constructor should return minimum value in the binary heap", String.valueOf((char) ('n' - i)), heap.get()); assertEquals("remove using default constructor should return minimum value in the binary heap", String.valueOf((char) ('n' - i)), heap.remove()); if (i + 1 < 14) { assertTrue("heap should not be empty before all elements are removed", !heap.isEmpty()); } else { assertTrue("heap should be empty after all elements are removed", heap.isEmpty()); } } try { heap.get(); fail("NoSuchElementException should be thrown if get is called after all elements are removed"); } catch (BufferUnderflowException ex) { } try { heap.remove(); fail("NoSuchElementException should be thrown if remove is called after all elements are removed"); } catch (BufferUnderflowException ex) { } } /** * Illustrates bad internal heap state reported in Bugzilla PR #235818. */ public void testAddRemove() { resetEmpty(); PriorityBuffer heap = (PriorityBuffer) collection; heap.add(new Integer(0)); heap.add(new Integer(2)); heap.add(new Integer(4)); heap.add(new Integer(3)); heap.add(new Integer(8)); heap.add(new Integer(10)); heap.add(new Integer(12)); heap.add(new Integer(3)); confirmed.addAll(heap); // System.out.println(heap); Object obj = new Integer(10); heap.remove(obj); confirmed.remove(obj); // System.out.println(heap); verify(); } /** * Generate heaps staring with Integers from 0 - heapSize - 1. * Then perform random add / remove operations, checking * heap order after modifications. Alternates minHeaps, maxHeaps. *

                  * Based on code provided by Steve Phelps in PR #25818 */ public void testRandom() { int iterations = 500; int heapSize = 100; int operations = 20; Random randGenerator = new Random(); PriorityBuffer h = null; for (int i = 0; i < iterations; i++) { if (i < iterations / 2) { h = new PriorityBuffer(true); } else { h = new PriorityBuffer(false); } for (int r = 0; r < heapSize; r++) { h.add(new Integer(randGenerator.nextInt(heapSize))); } for (int r = 0; r < operations; r++) { h.remove(new Integer(r)); h.add(new Integer(randGenerator.nextInt(heapSize))); } checkOrder(h); } } /** * Pops all elements from the heap and verifies that the elements come off * in the correct order. NOTE: this method empties the heap. */ protected void checkOrder(PriorityBuffer h) { Integer lastNum = null; Integer num = null; boolean fail = false; while (!h.isEmpty()) { num = (Integer) h.remove(); if (h.ascendingOrder) { assertTrue(lastNum == null || num.intValue() >= lastNum.intValue()); } else { // max heap assertTrue(lastNum == null || num.intValue() <= lastNum.intValue()); } lastNum = num; num = null; } } /** * Returns a string showing the contents of the heap formatted as a tree. * Makes no attempt at padding levels or handling wrapping. */ protected String showTree(PriorityBuffer h) { int count = 1; StringBuffer buffer = new StringBuffer(); for (int offset = 1; count < h.size() + 1; offset *= 2) { for (int i = offset; i < offset * 2; i++) { if (i < h.elements.length && h.elements[i] != null) buffer.append(h.elements[i] + " "); count++; } buffer.append('\n'); } return buffer.toString(); } } collections-generic-4.01/src/test/org/apache/commons/collections15/buffer/TestPredicatedBuffer.java0000644000175000017500000000735710464140762033703 0ustar giovannigiovanni/* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.buffer; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.collections15.ArrayStack; import org.apache.commons.collections15.Buffer; import org.apache.commons.collections15.BufferUnderflowException; import org.apache.commons.collections15.Predicate; import org.apache.commons.collections15.collection.TestPredicatedCollection; import java.util.Collection; /** * Extension of {@link TestPredicatedCollection} for exercising the * {@link PredicatedBuffer} implementation. * * @author Matt Hall, John Watkinson, Phil Steitz * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:44 $ * @since Commons Collections 3.0 */ public class TestPredicatedBuffer extends TestPredicatedCollection { public TestPredicatedBuffer(String testName) { super(testName); } public static Test suite() { return new TestSuite(TestPredicatedBuffer.class); } public static void main(String args[]) { String[] testCaseName = {TestPredicatedBuffer.class.getName()}; junit.textui.TestRunner.main(testCaseName); } //--------------------------------------------------------------- protected Buffer decorateBuffer(Buffer buffer, Predicate predicate) { return PredicatedBuffer.decorate(buffer, predicate); } public Collection makeCollection() { return decorateBuffer(new ArrayStack(), truePredicate); } public Collection makeConfirmedCollection() { return new ArrayStack(); } public Collection makeConfirmedFullCollection() { ArrayStack list = new ArrayStack(); list.addAll(java.util.Arrays.asList(getFullElements())); return list; } //------------------------------------------------------------ public Buffer makeTestBuffer() { return decorateBuffer(new ArrayStack(), testPredicate); } public void testGet() { Buffer buffer = makeTestBuffer(); try { Object o = buffer.get(); fail("Expecting BufferUnderflowException"); } catch (BufferUnderflowException ex) { // expected } buffer.add("one"); buffer.add("two"); buffer.add("three"); assertEquals("Buffer get", buffer.get(), "three"); } public void testRemove() { Buffer buffer = makeTestBuffer(); buffer.add("one"); assertEquals("Buffer get", buffer.remove(), "one"); try { buffer.remove(); fail("Expecting BufferUnderflowException"); } catch (BufferUnderflowException ex) { // expected } } public String getCompatibilityVersion() { return "3.1"; } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk((java.io.Serializable) collection, "D:/dev/collections15/data/test/PredicatedBuffer.emptyCollection.version3.1.obj"); // resetFull(); // writeExternalFormToDisk((java.io.Serializable) collection, "D:/dev/collections15/data/test/PredicatedBuffer.fullCollection.version3.1.obj"); // } } collections-generic-4.01/src/test/org/apache/commons/collections15/buffer/TestAll.java0000644000175000017500000000353510464140763031210 0ustar giovannigiovanni/* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.buffer; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * Entry point for tests. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:44 $ * @since Commons Collections 3.0 */ public class TestAll extends TestCase { public TestAll(String testName) { super(testName); } public static void main(String args[]) { String[] testCaseName = {TestAll.class.getName()}; junit.textui.TestRunner.main(testCaseName); } public static Test suite() { TestSuite suite = new TestSuite(); suite.addTest(TestBoundedFifoBuffer.suite()); suite.addTest(TestBoundedFifoBuffer2.suite()); suite.addTest(TestCircularFifoBuffer.suite()); suite.addTest(TestPriorityBuffer.suite()); suite.addTest(TestUnboundedFifoBuffer.suite()); suite.addTest(TestBlockingBuffer.suite()); suite.addTest(TestPredicatedBuffer.suite()); suite.addTest(TestSynchronizedBuffer.suite()); suite.addTest(TestTransformedBuffer.suite()); suite.addTest(TestUnmodifiableBuffer.suite()); return suite; } } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootcollections-generic-4.01/src/test/org/apache/commons/collections15/buffer/TestUnmodifiableBuffer.javacollections-generic-4.01/src/test/org/apache/commons/collections15/buffer/TestUnmodifiableBuffer.jav0000644000175000017500000000645010464140760034063 0ustar giovannigiovanni/* * Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.buffer; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.collections15.ArrayStack; import org.apache.commons.collections15.Buffer; import org.apache.commons.collections15.collection.AbstractTestCollection; import java.util.Arrays; import java.util.Collection; /** * Extension of {@link AbstractTestCollection} for exercising the * {@link UnmodifiableBuffer} implementation. * * @author Phil Steitz * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:44 $ * @since Commons Collections 3.1 */ public class TestUnmodifiableBuffer extends AbstractTestCollection { public TestUnmodifiableBuffer(String testName) { super(testName); } public static Test suite() { return new TestSuite(TestUnmodifiableBuffer.class); } public static void main(String args[]) { String[] testCaseName = {TestUnmodifiableBuffer.class.getName()}; junit.textui.TestRunner.main(testCaseName); } //----------------------------------------------------------------------- public Collection makeCollection() { return UnmodifiableBuffer.decorate(new UnboundedFifoBuffer()); } public Collection makeFullCollection() { Buffer buffer = new UnboundedFifoBuffer(); buffer.addAll(Arrays.asList(getFullElements())); return UnmodifiableBuffer.decorate(buffer); } public Collection makeConfirmedCollection() { ArrayStack list = new ArrayStack(); return list; } public Collection makeConfirmedFullCollection() { ArrayStack list = new ArrayStack(); list.addAll(Arrays.asList(getFullElements())); return list; } public boolean isAddSupported() { return false; } public boolean isRemoveSupported() { return false; } public boolean isNullSupported() { return false; } public void testBufferRemove() { resetEmpty(); Buffer buffer = (Buffer) collection; try { buffer.remove(); fail(); } catch (UnsupportedOperationException ex) { } } public String getCompatibilityVersion() { return "3.1"; } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk((java.io.Serializable) collection, "D:/dev/collections15/data/test/UnmodifiableBuffer.emptyCollection.version3.1.obj"); // resetFull(); // writeExternalFormToDisk((java.io.Serializable) collection, "D:/dev/collections15/data/test/UnmodifiableBuffer.fullCollection.version3.1.obj"); // } } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootcollections-generic-4.01/src/test/org/apache/commons/collections15/buffer/TestSynchronizedBuffer.javacollections-generic-4.01/src/test/org/apache/commons/collections15/buffer/TestSynchronizedBuffer.jav0000644000175000017500000000566210464140762034152 0ustar giovannigiovanni/* * Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.buffer; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.collections15.ArrayStack; import org.apache.commons.collections15.Buffer; import org.apache.commons.collections15.collection.AbstractTestCollection; import java.util.Arrays; import java.util.Collection; /** * Extension of {@link AbstractTestCollection} for exercising the * {@link SynchronizedBuffer} implementation. * * @author Phil Steitz * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:44 $ * @since Commons Collections 3.1 */ public class TestSynchronizedBuffer extends AbstractTestCollection { public TestSynchronizedBuffer(String testName) { super(testName); } public static Test suite() { return new TestSuite(TestSynchronizedBuffer.class); } public static void main(String args[]) { String[] testCaseName = {TestSynchronizedBuffer.class.getName()}; junit.textui.TestRunner.main(testCaseName); } //----------------------------------------------------------------------- public Collection makeCollection() { return SynchronizedBuffer.decorate(new UnboundedFifoBuffer()); } public Collection makeFullCollection() { Buffer buffer = new UnboundedFifoBuffer(); buffer.addAll(Arrays.asList(getFullElements())); return SynchronizedBuffer.decorate(buffer); } public Collection makeConfirmedCollection() { ArrayStack list = new ArrayStack(); return list; } public Collection makeConfirmedFullCollection() { ArrayStack list = new ArrayStack(); list.addAll(Arrays.asList(getFullElements())); return list; } public boolean isNullSupported() { return false; } public String getCompatibilityVersion() { return "3.1"; } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk((java.io.Serializable) collection, "D:/dev/collections15/data/test/SynchronizedBuffer.emptyCollection.version3.1.obj"); // resetFull(); // writeExternalFormToDisk((java.io.Serializable) collection, "D:/dev/collections15/data/test/SynchronizedBuffer.fullCollection.version3.1.obj"); // } } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootcollections-generic-4.01/src/test/org/apache/commons/collections15/buffer/TestUnboundedFifoBuffer.javacollections-generic-4.01/src/test/org/apache/commons/collections15/buffer/TestUnboundedFifoBuffer.ja0000644000175000017500000001121010464140754034017 0ustar giovannigiovanni/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.buffer; import junit.framework.Test; import org.apache.commons.collections15.BulkTest; import org.apache.commons.collections15.collection.AbstractTestCollection; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; /** * Test cases for UnboundedFifoBuffer. * * @author Matt Hall, John Watkinson, Unknown * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:44 $ */ public class TestUnboundedFifoBuffer extends AbstractTestCollection { public TestUnboundedFifoBuffer(String n) { super(n); } public static Test suite() { return BulkTest.makeSuite(TestUnboundedFifoBuffer.class); } //----------------------------------------------------------------------- /** * Verifies that the ArrayList has the same elements in the same * sequence as the UnboundedFifoBuffer. */ public void verify() { super.verify(); Iterator iterator1 = collection.iterator(); Iterator iterator2 = confirmed.iterator(); while (iterator2.hasNext()) { assertTrue(iterator1.hasNext()); Object o1 = iterator1.next(); Object o2 = iterator2.next(); assertEquals(o1, o2); } } //----------------------------------------------------------------------- /** * Overridden because UnboundedFifoBuffer doesn't allow null elements. * * @return false */ public boolean isNullSupported() { return false; } /** * Overridden because UnboundedFifoBuffer isn't fail fast. * * @return false */ public boolean isFailFastSupported() { return false; } //----------------------------------------------------------------------- /** * Returns an empty ArrayList. * * @return an empty ArrayList */ public Collection makeConfirmedCollection() { return new ArrayList(); } /** * Returns a full ArrayList. * * @return a full ArrayList */ public Collection makeConfirmedFullCollection() { Collection c = makeConfirmedCollection(); c.addAll(java.util.Arrays.asList(getFullElements())); return c; } /** * Returns an empty UnboundedFifoBuffer with a small capacity. * * @return an empty UnboundedFifoBuffer */ public Collection makeCollection() { return new UnboundedFifoBuffer(5); } //----------------------------------------------------------------------- /** * Tests that UnboundedFifoBuffer removes elements in the right order. */ public void testUnboundedFifoBufferRemove() { resetFull(); int size = confirmed.size(); for (int i = 0; i < size; i++) { Object o1 = ((UnboundedFifoBuffer) collection).remove(); Object o2 = ((ArrayList) confirmed).remove(0); assertEquals("Removed objects should be equal", o1, o2); verify(); } } /** * Tests that the constructor correctly throws an exception. */ public void testConstructorException1() { try { new UnboundedFifoBuffer(0); } catch (IllegalArgumentException ex) { return; } fail(); } /** * Tests that the constructor correctly throws an exception. */ public void testConstructorException2() { try { new UnboundedFifoBuffer(-20); } catch (IllegalArgumentException ex) { return; } fail(); } public String getCompatibilityVersion() { return "3.1"; } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk((java.io.Serializable) collection, "D:/dev/collections15/data/test/UnboundedFifoBuffer.emptyCollection.version3.1.obj"); // resetFull(); // writeExternalFormToDisk((java.io.Serializable) collection, "D:/dev/collections15/data/test/UnboundedFifoBuffer.fullCollection.version3.1.obj"); // } } collections-generic-4.01/src/test/org/apache/commons/collections15/TestTreeMap.java0000644000175000017500000000343510464140760030560 0ustar giovannigiovanni/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15; import org.apache.commons.collections15.map.AbstractTestMap; import java.util.TreeMap; /** * Tests TreeMap. * * @author Matt Hall, John Watkinson, Jason van Zyl * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:39 $ */ public abstract class TestTreeMap extends AbstractTestMap { public TestTreeMap(String testName) { super(testName); } public static void main(String args[]) { String[] testCaseName = {TestTreeMap.class.getName()}; junit.textui.TestRunner.main(testCaseName); } public boolean isAllowNullKey() { return false; } protected TreeMap map = null; public void setUp() { map = (TreeMap) makeEmptyMap(); } public void testNewMap() { assertTrue("New map is empty", map.isEmpty()); assertEquals("New map has size zero", map.size(), 0); } public void testSearch() { map.put("first", "First Item"); map.put("second", "Second Item"); assertEquals("Top item is 'Second Item'", map.get("first"), "First Item"); assertEquals("Next Item is 'First Item'", map.get("second"), "Second Item"); } } collections-generic-4.01/src/test/org/apache/commons/collections15/map/0000755000175000017500000000000011664401370026270 5ustar giovannigiovannicollections-generic-4.01/src/test/org/apache/commons/collections15/map/TestLazySortedMap.java0000644000175000017500000001223010464140761032530 0ustar giovannigiovanni/* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.map; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.collections15.Factory; import org.apache.commons.collections15.FactoryUtils; import java.util.Comparator; import java.util.Map; import java.util.SortedMap; import java.util.TreeMap; /** * Extension of {@link TestLazyMap} for exercising the * {@link LazySortedMap} implementation. * * @author Matt Hall, John Watkinson, Phil Steitz * @version $Revision: 1.1 $ $Date: 2005/10/11 19:11:58 $ * @since Commons Collections 3.0 */ public class TestLazySortedMap extends AbstractTestSortedMap { protected static final Factory oneFactory = FactoryUtils.constantFactory("One"); protected static final Factory nullFactory = FactoryUtils.nullFactory(); public TestLazySortedMap(String testName) { super(testName); } public static Test suite() { return new TestSuite(TestLazySortedMap.class); } public static void main(String args[]) { String[] testCaseName = {TestLazySortedMap.class.getName()}; junit.textui.TestRunner.main(testCaseName); } //----------------------------------------------------------------------- protected SortedMap decorateMap(SortedMap map, Factory factory) { return LazySortedMap.decorate(map, factory); } public Map makeEmptyMap() { return decorateMap(new TreeMap(), nullFactory); } protected SortedMap makeTestSortedMap(Factory factory) { return decorateMap(new TreeMap(), factory); } public boolean isSubMapViewsSerializable() { // TreeMap sub map views have a bug in deserialization. return false; } public boolean isAllowNullKey() { return false; } // from TestLazyMap //----------------------------------------------------------------------- public void testMapGet() { Map map = makeTestSortedMap(oneFactory); assertEquals(0, map.size()); String s1 = (String) map.get("Five"); assertEquals("One", s1); assertEquals(1, map.size()); String s2 = (String) map.get(new String(new char[]{'F', 'i', 'v', 'e'})); assertEquals("One", s2); assertEquals(1, map.size()); assertSame(s1, s2); map = makeTestSortedMap(nullFactory); Object o = map.get("Five"); assertEquals(null, o); assertEquals(1, map.size()); } //----------------------------------------------------------------------- public void testSortOrder() { SortedMap map = makeTestSortedMap(oneFactory); map.put("A", "a"); map.get("B"); // Entry with value "One" created map.put("C", "c"); assertEquals("First key should be A", map.firstKey(), "A"); assertEquals("Last key should be C", map.lastKey(), "C"); assertEquals("First key in tail map should be B", map.tailMap("B").firstKey(), "B"); assertEquals("Last key in head map should be B", map.headMap("C").lastKey(), "B"); assertEquals("Last key in submap should be B", map.subMap("A", "C").lastKey(), "B"); Comparator c = map.comparator(); assertTrue("natural order, so comparator should be null", c == null); } /* public void testTransformerDecorate() { Transformer transformer = TransformerUtils.asTransformer(oneFactory); SortedMap map = LazySortedMap.decorate(new TreeMap(), transformer); assertTrue(map instanceof LazySortedMap); try { map = LazySortedMap.decorate(new TreeMap(), (Transformer) null); fail("Expecting IllegalArgumentException for null transformer"); } catch (IllegalArgumentException e) { // expected } try { map = LazySortedMap.decorate(null, transformer); fail("Expecting IllegalArgumentException for null map"); } catch (IllegalArgumentException e) { // expected } } */ public String getCompatibilityVersion() { return "3.1"; } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk( // (java.io.Serializable) map, // "D:/dev/collections15/data/test/LazySortedMap.emptyCollection.version3.1.obj"); // resetFull(); // writeExternalFormToDisk( // (java.io.Serializable) map, // "D:/dev/collections15/data/test/LazySortedMap.fullCollection.version3.1.obj"); // } }collections-generic-4.01/src/test/org/apache/commons/collections15/map/AbstractTestIterableMap.java0000644000175000017500000001222510464140764033652 0ustar giovannigiovanni/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.map; import org.apache.commons.collections15.BulkTest; import org.apache.commons.collections15.IterableMap; import org.apache.commons.collections15.MapIterator; import org.apache.commons.collections15.iterators.AbstractTestMapIterator; import java.util.ConcurrentModificationException; import java.util.Iterator; import java.util.Map; /** * Abstract test class for {@link IterableMap} methods and contracts. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 19:11:58 $ */ public abstract class AbstractTestIterableMap extends AbstractTestMap { /** * JUnit constructor. * * @param testName the test name */ public AbstractTestIterableMap(String testName) { super(testName); } //----------------------------------------------------------------------- public void testFailFastEntrySet() { if (isRemoveSupported() == false) return; resetFull(); Iterator it = map.entrySet().iterator(); Map.Entry val = (Map.Entry) it.next(); map.remove(val.getKey()); try { it.next(); fail(); } catch (ConcurrentModificationException ex) { } resetFull(); it = map.entrySet().iterator(); it.next(); map.clear(); try { it.next(); fail(); } catch (ConcurrentModificationException ex) { } } public void testFailFastKeySet() { if (isRemoveSupported() == false) return; resetFull(); Iterator it = map.keySet().iterator(); Object val = it.next(); map.remove(val); try { it.next(); fail(); } catch (ConcurrentModificationException ex) { } resetFull(); it = map.keySet().iterator(); it.next(); map.clear(); try { it.next(); fail(); } catch (ConcurrentModificationException ex) { } } public void testFailFastValues() { if (isRemoveSupported() == false) return; resetFull(); Iterator it = map.values().iterator(); it.next(); map.remove(map.keySet().iterator().next()); try { it.next(); fail(); } catch (ConcurrentModificationException ex) { } resetFull(); it = map.values().iterator(); it.next(); map.clear(); try { it.next(); fail(); } catch (ConcurrentModificationException ex) { } } //----------------------------------------------------------------------- public BulkTest bulkTestMapIterator() { return new InnerTestMapIterator(); } public class InnerTestMapIterator extends AbstractTestMapIterator { public InnerTestMapIterator() { super("InnerTestMapIterator"); } public Object[] addSetValues() { return AbstractTestIterableMap.this.getNewSampleValues(); } public boolean supportsRemove() { return AbstractTestIterableMap.this.isRemoveSupported(); } public boolean isGetStructuralModify() { return AbstractTestIterableMap.this.isGetStructuralModify(); } public boolean supportsSetValue() { return AbstractTestIterableMap.this.isSetValueSupported(); } public MapIterator makeEmptyMapIterator() { resetEmpty(); return ((IterableMap) AbstractTestIterableMap.this.map).mapIterator(); } public MapIterator makeFullMapIterator() { resetFull(); return ((IterableMap) AbstractTestIterableMap.this.map).mapIterator(); } public Map getMap() { // assumes makeFullMapIterator() called first return AbstractTestIterableMap.this.map; } public Map getConfirmedMap() { // assumes makeFullMapIterator() called first return AbstractTestIterableMap.this.confirmed; } public void verify() { super.verify(); AbstractTestIterableMap.this.verify(); } } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk((Serializable) map, "D:/dev/collections15/data/test/HashedMap.emptyCollection.version3.obj"); // resetFull(); // writeExternalFormToDisk((Serializable) map, "D:/dev/collections15/data/test/HashedMap.fullCollection.version3.obj"); // } } collections-generic-4.01/src/test/org/apache/commons/collections15/map/TestStaticBucketMap.java0000644000175000017500000000330010464140764033016 0ustar giovannigiovanni/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.map; import junit.framework.Test; import org.apache.commons.collections15.BulkTest; import java.util.Map; /** * Unit tests * {@link org.apache.commons.collections15.StaticBucketMap}. * * @author Matt Hall, John Watkinson, Michael A. Smith * @version $Revision: 1.1 $ $Date: 2005/10/11 19:11:58 $ */ public class TestStaticBucketMap extends AbstractTestMap { public TestStaticBucketMap(String name) { super(name); } public static Test suite() { return BulkTest.makeSuite(TestStaticBucketMap.class); } public static void main(String[] args[]) { String[] testCaseName = {TestStaticBucketMap.class.getName()}; junit.textui.TestRunner.main(testCaseName); } public Map makeEmptyMap() { return new StaticBucketMap(30); } public String[] ignoredTests() { String pre = "TestStaticBucketMap.bulkTestMap"; String post = ".testCollectionIteratorFailFast"; return new String[]{pre + "EntrySet" + post, pre + "KeySet" + post, pre + "Values" + post}; } } collections-generic-4.01/src/test/org/apache/commons/collections15/map/TestReferenceIdentityMap.java0000644000175000017500000002617610464140762034057 0ustar giovannigiovanni/* * Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.map; import junit.framework.Test; import org.apache.commons.collections15.BulkTest; import org.apache.commons.collections15.IterableMap; import java.lang.ref.WeakReference; import java.util.Iterator; import java.util.Map; /** * Tests for ReferenceIdentityMap. * * @author Paul Jack * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ */ public class TestReferenceIdentityMap extends AbstractTestIterableMap { private static final Integer I1A = new Integer(1); private static final Integer I1B = new Integer(1); private static final Integer I2A = new Integer(2); private static final Integer I2B = new Integer(2); public TestReferenceIdentityMap(String testName) { super(testName); } public static Test suite() { return BulkTest.makeSuite(TestReferenceIdentityMap.class); } public static void main(String args[]) { String[] testCaseName = {TestReferenceIdentityMap.class.getName()}; junit.textui.TestRunner.main(testCaseName); } public Map makeEmptyMap() { ReferenceIdentityMap map = new ReferenceIdentityMap(ReferenceIdentityMap.WEAK, ReferenceIdentityMap.WEAK); return map; } public Map makeConfirmedMap() { // Testing against another [collections15] class generally isn't a good idea, // but the alternative is a JDK1.4 dependency in the tests return new IdentityMap(); } public boolean isAllowNullKey() { return false; } public boolean isAllowNullValue() { return false; } public String getCompatibilityVersion() { return "3.1"; } //----------------------------------------------------------------------- public void testBasics() { IterableMap map = new ReferenceIdentityMap(ReferenceIdentityMap.HARD, ReferenceIdentityMap.HARD); assertEquals(0, map.size()); map.put(I1A, I2A); assertEquals(1, map.size()); assertSame(I2A, map.get(I1A)); assertSame(null, map.get(I1B)); assertEquals(true, map.containsKey(I1A)); assertEquals(false, map.containsKey(I1B)); assertEquals(true, map.containsValue(I2A)); assertEquals(false, map.containsValue(I2B)); map.put(I1A, I2B); assertEquals(1, map.size()); assertSame(I2B, map.get(I1A)); assertSame(null, map.get(I1B)); assertEquals(true, map.containsKey(I1A)); assertEquals(false, map.containsKey(I1B)); assertEquals(false, map.containsValue(I2A)); assertEquals(true, map.containsValue(I2B)); map.put(I1B, I2B); assertEquals(2, map.size()); assertSame(I2B, map.get(I1A)); assertSame(I2B, map.get(I1B)); assertEquals(true, map.containsKey(I1A)); assertEquals(true, map.containsKey(I1B)); assertEquals(false, map.containsValue(I2A)); assertEquals(true, map.containsValue(I2B)); } //----------------------------------------------------------------------- public void testHashEntry() { IterableMap map = new ReferenceIdentityMap(ReferenceIdentityMap.HARD, ReferenceIdentityMap.HARD); map.put(I1A, I2A); map.put(I1B, I2A); Map.Entry entry1 = (Map.Entry) map.entrySet().iterator().next(); Iterator it = map.entrySet().iterator(); Map.Entry entry2 = (Map.Entry) it.next(); Map.Entry entry3 = (Map.Entry) it.next(); assertEquals(true, entry1.equals(entry2)); assertEquals(true, entry2.equals(entry1)); assertEquals(false, entry1.equals(entry3)); } //----------------------------------------------------------------------- public void testNullHandling() { resetFull(); assertEquals(null, map.get(null)); assertEquals(false, map.containsKey(null)); assertEquals(false, map.containsValue(null)); assertEquals(null, map.remove(null)); assertEquals(false, map.entrySet().contains(null)); assertEquals(false, map.keySet().contains(null)); assertEquals(false, map.values().contains(null)); try { map.put(null, null); fail(); } catch (NullPointerException ex) { } try { map.put(new Object(), null); fail(); } catch (NullPointerException ex) { } try { map.put(null, new Object()); fail(); } catch (NullPointerException ex) { } } //----------------------------------------------------------------------- /* // Tests often fail because gc is uncontrollable public void testPurge() { ReferenceIdentityMap map = new ReferenceIdentityMap(ReferenceIdentityMap.WEAK, ReferenceIdentityMap.WEAK); Object[] hard = new Object[10]; for (int i = 0; i < hard.length; i++) { hard[i] = new Object(); map.put(hard[i], new Object()); } gc(); assertTrue("map should be empty after purge of weak values", map.isEmpty()); for (int i = 0; i < hard.length; i++) { map.put(new Object(), hard[i]); } gc(); assertTrue("map should be empty after purge of weak keys", map.isEmpty()); for (int i = 0; i < hard.length; i++) { map.put(new Object(), hard[i]); map.put(hard[i], new Object()); } gc(); assertTrue("map should be empty after purge of weak keys and values", map.isEmpty()); } public void testGetAfterGC() { ReferenceIdentityMap map = new ReferenceIdentityMap(ReferenceIdentityMap.WEAK, ReferenceIdentityMap.WEAK); for (int i = 0; i < 10; i++) { map.put(new Integer(i), new Integer(i)); } gc(); for (int i = 0; i < 10; i++) { Integer I = new Integer(i); assertTrue("map.containsKey should return false for GC'd element", !map.containsKey(I)); assertTrue("map.get should return null for GC'd element", map.get(I) == null); } } public void testEntrySetIteratorAfterGC() { ReferenceIdentityMap map = new ReferenceIdentityMap(ReferenceIdentityMap.WEAK, ReferenceIdentityMap.WEAK); Object[] hard = new Object[10]; for (int i = 0; i < 10; i++) { hard[i] = new Integer(10 + i); map.put(new Integer(i), new Integer(i)); map.put(hard[i], hard[i]); } gc(); Iterator iterator = map.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry entry = (Map.Entry)iterator.next(); Integer key = (Integer)entry.getKey(); Integer value = (Integer)entry.getValue(); assertTrue("iterator should skip GC'd keys", key.intValue() >= 10); assertTrue("iterator should skip GC'd values", value.intValue() >= 10); } } public void testMapIteratorAfterGC() { ReferenceIdentityMap map = new ReferenceIdentityMap(ReferenceIdentityMap.WEAK, ReferenceIdentityMap.WEAK); Object[] hard = new Object[10]; for (int i = 0; i < 10; i++) { hard[i] = new Integer(10 + i); map.put(new Integer(i), new Integer(i)); map.put(hard[i], hard[i]); } gc(); MapIterator iterator = map.mapIterator(); while (iterator.hasNext()) { Object key1 = iterator.next(); Integer key = (Integer) iterator.getKey(); Integer value = (Integer) iterator.getValue(); assertTrue("iterator keys should match", key == key1); assertTrue("iterator should skip GC'd keys", key.intValue() >= 10); assertTrue("iterator should skip GC'd values", value.intValue() >= 10); } } public void testMapIteratorAfterGC2() { ReferenceIdentityMap map = new ReferenceIdentityMap(ReferenceIdentityMap.WEAK, ReferenceIdentityMap.WEAK); Object[] hard = new Object[10]; for (int i = 0; i < 10; i++) { hard[i] = new Integer(10 + i); map.put(new Integer(i), new Integer(i)); map.put(hard[i], hard[i]); } MapIterator iterator = map.mapIterator(); while (iterator.hasNext()) { Object key1 = iterator.next(); gc(); Integer key = (Integer) iterator.getKey(); Integer value = (Integer) iterator.getValue(); assertTrue("iterator keys should match", key == key1); assertTrue("iterator should skip GC'd keys", key.intValue() >= 10); assertTrue("iterator should skip GC'd values", value.intValue() >= 10); } } */ /** * Tests whether purge values setting works */ public void testPurgeValues() throws Exception { // many thanks to Juozas Baliuka for suggesting this method Object key = new Object(); Object value = new Object(); WeakReference keyReference = new WeakReference(key); WeakReference valueReference = new WeakReference(value); Map testMap = new ReferenceIdentityMap(ReferenceIdentityMap.WEAK, ReferenceIdentityMap.HARD, true); testMap.put(key, value); assertEquals("In map", value, testMap.get(key)); assertNotNull("Weak reference released early (1)", keyReference.get()); assertNotNull("Weak reference released early (2)", valueReference.get()); // dereference strong references key = null; value = null; int iterations = 0; int bytz = 2; while (true) { System.gc(); if (iterations++ > 50) { fail("Max iterations reached before resource released."); } testMap.isEmpty(); if (keyReference.get() == null && valueReference.get() == null) { break; } else { // create garbage: byte[] b = new byte[bytz]; bytz = bytz * 2; } } } private static void gc() { try { // trigger GC byte[][] tooLarge = new byte[1000000000][1000000000]; fail("you have too much RAM"); } catch (OutOfMemoryError ex) { System.gc(); // ignore } } } collections-generic-4.01/src/test/org/apache/commons/collections15/map/AbstractTestMap.java0000644000175000017500000016370510464140765032215 0ustar giovannigiovanni/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.map; import org.apache.commons.collections15.AbstractTestObject; import org.apache.commons.collections15.BulkTest; import org.apache.commons.collections15.collection.AbstractTestCollection; import org.apache.commons.collections15.set.AbstractTestSet; import java.util.*; /** * Abstract test class for {@link java.util.Map} methods and contracts. *

                  * The forces at work here are similar to those in {@link AbstractTestCollection}. * If your class implements the full Map interface, including optional * operations, simply extend this class, and implement the * {@link #makeEmptyMap()} method. *

                  * On the other hand, if your map implementation is weird, you may have to * override one or more of the other protected methods. They're described * below. *

                  * Entry Population Methods *

                  * Override these methods if your map requires special entries: *

                  *

                    *
                  • {@link #getSampleKeys()} *
                  • {@link #getSampleValues()} *
                  • {@link #getNewSampleValues()} *
                  • {@link #getOtherKeys()} *
                  • {@link #getOtherValues()} *
                  *

                  * Supported Operation Methods *

                  * Override these methods if your map doesn't support certain operations: *

                  *

                    *
                  • {@link #isPutAddSupported()} *
                  • {@link #isPutChangeSupported()} *
                  • {@link #isSetValueSupported()} *
                  • {@link #isRemoveSupported()} *
                  • {@link #isGetStructuralModify()} *
                  • {@link #isAllowDuplicateValues()} *
                  • {@link #isAllowNullKey()} *
                  • {@link #isAllowNullValue()} *
                  *

                  * Fixture Methods *

                  * For tests on modification operations (puts and removes), fixtures are used * to verify that that operation results in correct state for the map and its * collection views. Basically, the modification is performed against your * map implementation, and an identical modification is performed against * a confirmed map implementation. A confirmed map implementation is * something like java.util.HashMap, which is known to conform * exactly to the {@link Map} contract. After the modification takes place * on both your map implementation and the confirmed map implementation, the * two maps are compared to see if their state is identical. The comparison * also compares the collection views to make sure they're still the same.

                  *

                  * The upshot of all that is that any test that modifies the map in * any way will verify that all of the map's state is still * correct, including the state of its collection views. So for instance * if a key is removed by the map's key set's iterator, then the entry set * is checked to make sure the key/value pair no longer appears.

                  *

                  * The {@link #map} field holds an instance of your collection implementation. * The {@link #entrySet}, {@link #keySet} and {@link #values} fields hold * that map's collection views. And the {@link #confirmed} field holds * an instance of the confirmed collection implementation. The * {@link #resetEmpty()} and {@link #resetFull()} methods set these fields to * empty or full maps, so that tests can proceed from a known state.

                  *

                  * After a modification operation to both {@link #map} and {@link #confirmed}, * the {@link #verify()} method is invoked to compare the results. The * {@link #verify} method calls separate methods to verify the map and its three * collection views ({@link #verifyMap}, {@link #verifyEntrySet}, * {@link #verifyKeySet}, and {@link #verifyValues}). You may want to override * one of the verification methodsto perform additional verifications. For * instance, TestDoubleOrderedMap would want override its * {@link #verifyValues()} method to verify that the values are unique and in * ascending order.

                  *

                  * Other Notes *

                  * If your {@link Map} fails one of these tests by design, you may still use * this base set of cases. Simply override the test case (method) your map * fails and/or the methods that define the assumptions used by the test * cases. For example, if your map does not allow duplicate values, override * {@link #isAllowDuplicateValues()} and have it return false * * @author Michael Smith * @author Rodney Waldhoff * @author Paul Jack * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 19:11:58 $ */ public abstract class AbstractTestMap extends AbstractTestObject { /** * JDK1.2 has bugs in null handling of Maps, especially HashMap.Entry.toString * This avoids nulls for JDK1.2 */ private static final boolean JDK12; static { String str = System.getProperty("java.version"); JDK12 = str.startsWith("1.2"); } // These instance variables are initialized with the reset method. // Tests for map methods that alter the map (put, putAll, remove) // first call reset() to create the map and its views; then perform // the modification on the map; perform the same modification on the // confirmed; and then call verify() to ensure that the map is equal // to the confirmed, that the already-constructed collection views // are still equal to the confirmed's collection views. /** * Map created by reset(). */ protected Map map; /** * Entry set of map created by reset(). */ protected Set entrySet; /** * Key set of map created by reset(). */ protected Set keySet; /** * Values collection of map created by reset(). */ protected Collection values; /** * HashMap created by reset(). */ protected Map confirmed; /** * JUnit constructor. * * @param testName the test name */ public AbstractTestMap(String testName) { super(testName); } /** * Returns true if the maps produced by * {@link #makeEmptyMap()} and {@link #makeFullMap()} * support the put and putAll operations * adding new mappings. *

                  * Default implementation returns true. * Override if your collection class does not support put adding. */ public boolean isPutAddSupported() { return true; } /** * Returns true if the maps produced by * {@link #makeEmptyMap()} and {@link #makeFullMap()} * support the put and putAll operations * changing existing mappings. *

                  * Default implementation returns true. * Override if your collection class does not support put changing. */ public boolean isPutChangeSupported() { return true; } /** * Returns true if the maps produced by * {@link #makeEmptyMap()} and {@link #makeFullMap()} * support the setValue operation on entrySet entries. *

                  * Default implementation returns isPutChangeSupported(). * Override if your collection class does not support setValue but does * support put changing. */ public boolean isSetValueSupported() { return isPutChangeSupported(); } /** * Returns true if the maps produced by * {@link #makeEmptyMap()} and {@link #makeFullMap()} * support the remove and clear operations. *

                  * Default implementation returns true. * Override if your collection class does not support removal operations. */ public boolean isRemoveSupported() { return true; } /** * Returns true if the maps produced by * {@link #makeEmptyMap()} and {@link #makeFullMap()} * can cause structural modification on a get(). The example is LRUMap. *

                  * Default implementation returns false. * Override if your map class structurally modifies on get. */ public boolean isGetStructuralModify() { return false; } /** * Returns whether the sub map views of SortedMap are serializable. * If the class being tested is based around a TreeMap then you should * override and return false as TreeMap has a bug in deserialization. * * @return false */ public boolean isSubMapViewsSerializable() { return true; } /** * Returns true if the maps produced by * {@link #makeEmptyMap()} and {@link #makeFullMap()} * supports null keys. *

                  * Default implementation returns true. * Override if your collection class does not support null keys. */ public boolean isAllowNullKey() { return true; } /** * Returns true if the maps produced by * {@link #makeEmptyMap()} and {@link #makeFullMap()} * supports null values. *

                  * Default implementation returns true. * Override if your collection class does not support null values. */ public boolean isAllowNullValue() { return true; } /** * Returns true if the maps produced by * {@link #makeEmptyMap()} and {@link #makeFullMap()} * supports duplicate values. *

                  * Default implementation returns true. * Override if your collection class does not support duplicate values. */ public boolean isAllowDuplicateValues() { return true; } /** * Returns the set of keys in the mappings used to test the map. This * method must return an array with the same length as {@link * #getSampleValues()} and all array elements must be different. The * default implementation constructs a set of String keys, and includes a * single null key if {@link #isAllowNullKey()} returns true. */ public Object[] getSampleKeys() { Object[] result = new Object[]{"blah", "foo", "bar", "baz", "tmp", "gosh", "golly", "gee", "hello", "goodbye", "we'll", "see", "you", "all", "again", "key", "key2", (isAllowNullKey() && !JDK12) ? null : "nonnullkey"}; return result; } public Object[] getOtherKeys() { return getOtherNonNullStringElements(); } public Object[] getOtherValues() { return getOtherNonNullStringElements(); } /** * Returns a list of string elements suitable for return by * {@link #getOtherKeys()} or {@link #getOtherValues}. *

                  *

                  Override getOtherElements to returnthe results of this method if your * collection does not support heterogenous elements or the null element. *

                  */ public Object[] getOtherNonNullStringElements() { return new Object[]{"For", "then", "despite", /* of */"space", "I", "would", "be", "brought", "From", "limits", "far", "remote", "where", "thou", "dost", "stay"}; } /** * Returns the set of values in the mappings used to test the map. This * method must return an array with the same length as * {@link #getSampleKeys()}. The default implementation constructs a set of * String values and includes a single null value if * {@link #isAllowNullValue()} returns true, and includes * two values that are the same if {@link #isAllowDuplicateValues()} returns * true. */ public Object[] getSampleValues() { Object[] result = new Object[]{"blahv", "foov", "barv", "bazv", "tmpv", "goshv", "gollyv", "geev", "hellov", "goodbyev", "we'llv", "seev", "youv", "allv", "againv", (isAllowNullValue() && !JDK12) ? null : "nonnullvalue", "value", (isAllowDuplicateValues()) ? "value" : "value2", }; return result; } /** * Returns a the set of values that can be used to replace the values * returned from {@link #getSampleValues()}. This method must return an * array with the same length as {@link #getSampleValues()}. The values * returned from this method should not be the same as those returned from * {@link #getSampleValues()}. The default implementation constructs a * set of String values and includes a single null value if * {@link #isAllowNullValue()} returns true, and includes two values * that are the same if {@link #isAllowDuplicateValues()} returns * true. */ public Object[] getNewSampleValues() { Object[] result = new Object[]{(isAllowNullValue() && !JDK12 && isAllowDuplicateValues()) ? null : "newnonnullvalue", "newvalue", (isAllowDuplicateValues()) ? "newvalue" : "newvalue2", "newblahv", "newfoov", "newbarv", "newbazv", "newtmpv", "newgoshv", "newgollyv", "newgeev", "newhellov", "newgoodbyev", "newwe'llv", "newseev", "newyouv", "newallv", "newagainv", }; return result; } /** * Helper method to add all the mappings described by * {@link #getSampleKeys()} and {@link #getSampleValues()}. */ public void addSampleMappings(Map m) { Object[] keys = getSampleKeys(); Object[] values = getSampleValues(); for (int i = 0; i < keys.length; i++) { try { m.put(keys[i], values[i]); } catch (NullPointerException exception) { assertTrue("NullPointerException only allowed to be thrown " + "if either the key or value is null.", keys[i] == null || values[i] == null); assertTrue("NullPointerException on null key, but " + "isAllowNullKey is not overridden to return false.", keys[i] == null || !isAllowNullKey()); assertTrue("NullPointerException on null value, but " + "isAllowNullValue is not overridden to return false.", values[i] == null || !isAllowNullValue()); assertTrue("Unknown reason for NullPointer.", false); } } assertEquals("size must reflect number of mappings added.", keys.length, m.size()); } //----------------------------------------------------------------------- /** * Return a new, empty {@link Map} to be used for testing. * * @return the map to be tested */ public abstract Map makeEmptyMap(); /** * Return a new, populated map. The mappings in the map should match the * keys and values returned from {@link #getSampleKeys()} and * {@link #getSampleValues()}. The default implementation uses makeEmptyMap() * and calls {@link #addSampleMappings} to add all the mappings to the * map. * * @return the map to be tested */ public Map makeFullMap() { Map m = makeEmptyMap(); addSampleMappings(m); return m; } /** * Implements the superclass method to return the map to be tested. * * @return the map to be tested */ public Object makeObject() { return makeEmptyMap(); } /** * Override to return a map other than HashMap as the confirmed map. * * @return a map that is known to be valid */ public Map makeConfirmedMap() { return new HashMap(); } /** * Creates a new Map Entry that is independent of the first and the map. */ public Map.Entry cloneMapEntry(Map.Entry entry) { HashMap map = new HashMap(); map.put(entry.getKey(), entry.getValue()); return (Map.Entry) map.entrySet().iterator().next(); } /** * Gets the compatability version, needed for package access. */ public String getCompatibilityVersion() { return super.getCompatibilityVersion(); } //----------------------------------------------------------------------- /** * Test to ensure the test setup is working properly. This method checks * to ensure that the getSampleKeys and getSampleValues methods are * returning results that look appropriate. That is, they both return a * non-null array of equal length. The keys array must not have any * duplicate values, and may only contain a (single) null key if * isNullKeySupported() returns true. The values array must only have a null * value if useNullValue() is true and may only have duplicate values if * isAllowDuplicateValues() returns true. */ public void testSampleMappings() { Object[] keys = getSampleKeys(); Object[] values = getSampleValues(); Object[] newValues = getNewSampleValues(); assertTrue("failure in test: Must have keys returned from " + "getSampleKeys.", keys != null); assertTrue("failure in test: Must have values returned from " + "getSampleValues.", values != null); // verify keys and values have equivalent lengths (in case getSampleX are // overridden) assertEquals("failure in test: not the same number of sample " + "keys and values.", keys.length, values.length); assertEquals("failure in test: not the same number of values and new values.", values.length, newValues.length); // verify there aren't duplicate keys, and check values for (int i = 0; i < keys.length - 1; i++) { for (int j = i + 1; j < keys.length; j++) { assertTrue("failure in test: duplicate null keys.", (keys[i] != null || keys[j] != null)); assertTrue("failure in test: duplicate non-null key.", (keys[i] == null || keys[j] == null || (!keys[i].equals(keys[j]) && !keys[j].equals(keys[i])))); } assertTrue("failure in test: found null key, but isNullKeySupported " + "is false.", keys[i] != null || isAllowNullKey()); assertTrue("failure in test: found null value, but isNullValueSupported " + "is false.", values[i] != null || isAllowNullValue()); assertTrue("failure in test: found null new value, but isNullValueSupported " + "is false.", newValues[i] != null || isAllowNullValue()); assertTrue("failure in test: values should not be the same as new value", values[i] != newValues[i] && (values[i] == null || !values[i].equals(newValues[i]))); } } // tests begin here. Each test adds a little bit of tested functionality. // Many methods assume previous methods passed. That is, they do not // exhaustively recheck things that have already been checked in a previous // test methods. /** * Test to ensure that makeEmptyMap and makeFull returns a new non-null * map with each invocation. */ public void testMakeMap() { Map em = makeEmptyMap(); assertTrue("failure in test: makeEmptyMap must return a non-null map.", em != null); Map em2 = makeEmptyMap(); assertTrue("failure in test: makeEmptyMap must return a non-null map.", em != null); assertTrue("failure in test: makeEmptyMap must return a new map " + "with each invocation.", em != em2); Map fm = makeFullMap(); assertTrue("failure in test: makeFullMap must return a non-null map.", fm != null); Map fm2 = makeFullMap(); assertTrue("failure in test: makeFullMap must return a non-null map.", fm != null); assertTrue("failure in test: makeFullMap must return a new map " + "with each invocation.", fm != fm2); } /** * Tests Map.isEmpty() */ public void testMapIsEmpty() { resetEmpty(); assertEquals("Map.isEmpty() should return true with an empty map", true, map.isEmpty()); verify(); resetFull(); assertEquals("Map.isEmpty() should return false with a non-empty map", false, map.isEmpty()); verify(); } /** * Tests Map.size() */ public void testMapSize() { resetEmpty(); assertEquals("Map.size() should be 0 with an empty map", 0, map.size()); verify(); resetFull(); assertEquals("Map.size() should equal the number of entries " + "in the map", getSampleKeys().length, map.size()); verify(); } /** * Tests {@link Map#clear()}. If the map {@link #isRemoveSupported()} * can add and remove elements}, then {@link Map#size()} and * {@link Map#isEmpty()} are used to ensure that map has no elements after * a call to clear. If the map does not support adding and removing * elements, this method checks to ensure clear throws an * UnsupportedOperationException. */ public void testMapClear() { if (!isRemoveSupported()) { try { resetFull(); map.clear(); fail("Expected UnsupportedOperationException on clear"); } catch (UnsupportedOperationException ex) { } return; } resetEmpty(); map.clear(); confirmed.clear(); verify(); resetFull(); map.clear(); confirmed.clear(); verify(); } /** * Tests Map.containsKey(Object) by verifying it returns false for all * sample keys on a map created using an empty map and returns true for * all sample keys returned on a full map. */ public void testMapContainsKey() { Object[] keys = getSampleKeys(); resetEmpty(); for (int i = 0; i < keys.length; i++) { assertTrue("Map must not contain key when map is empty", !map.containsKey(keys[i])); } verify(); resetFull(); for (int i = 0; i < keys.length; i++) { assertTrue("Map must contain key for a mapping in the map. " + "Missing: " + keys[i], map.containsKey(keys[i])); } verify(); } /** * Tests Map.containsValue(Object) by verifying it returns false for all * sample values on an empty map and returns true for all sample values on * a full map. */ public void testMapContainsValue() { Object[] values = getSampleValues(); resetEmpty(); for (int i = 0; i < values.length; i++) { assertTrue("Empty map must not contain value", !map.containsValue(values[i])); } verify(); resetFull(); for (int i = 0; i < values.length; i++) { assertTrue("Map must contain value for a mapping in the map.", map.containsValue(values[i])); } verify(); } /** * Tests Map.equals(Object) */ public void testMapEquals() { resetEmpty(); assertTrue("Empty maps unequal.", map.equals(confirmed)); verify(); resetFull(); assertTrue("Full maps unequal.", map.equals(confirmed)); verify(); resetFull(); // modify the HashMap created from the full map and make sure this // change results in map.equals() to return false. Iterator iter = confirmed.keySet().iterator(); iter.next(); iter.remove(); assertTrue("Different maps equal.", !map.equals(confirmed)); resetFull(); assertTrue("equals(null) returned true.", !map.equals(null)); assertTrue("equals(new Object()) returned true.", !map.equals(new Object())); verify(); } /** * Tests Map.get(Object) */ public void testMapGet() { resetEmpty(); Object[] keys = getSampleKeys(); Object[] values = getSampleValues(); for (int i = 0; i < keys.length; i++) { assertTrue("Empty map.get() should return null.", map.get(keys[i]) == null); } verify(); resetFull(); for (int i = 0; i < keys.length; i++) { assertEquals("Full map.get() should return value from mapping.", values[i], map.get(keys[i])); } } /** * Tests Map.hashCode() */ public void testMapHashCode() { resetEmpty(); assertTrue("Empty maps have different hashCodes.", map.hashCode() == confirmed.hashCode()); resetFull(); assertTrue("Equal maps have different hashCodes.", map.hashCode() == confirmed.hashCode()); } /** * Tests Map.toString(). Since the format of the string returned by the * toString() method is not defined in the Map interface, there is no * common way to test the results of the toString() method. Thereforce, * it is encouraged that Map implementations override this test with one * that checks the format matches any format defined in its API. This * default implementation just verifies that the toString() method does * not return null. */ public void testMapToString() { resetEmpty(); assertTrue("Empty map toString() should not return null", map.toString() != null); verify(); resetFull(); assertTrue("Empty map toString() should not return null", map.toString() != null); verify(); } /** * Compare the current serialized form of the Map * against the canonical version in CVS. */ public void testEmptyMapCompatibility() throws Exception { /** * Create canonical objects with this code Map map = makeEmptyMap(); if (!(map instanceof Serializable)) return; writeExternalFormToDisk((Serializable) map, getCanonicalEmptyCollectionName(map)); */ // test to make sure the canonical form has been preserved // GenericsNote: Serialized compatibility with older class versions is not supported for now //Map map = makeEmptyMap(); //if (map instanceof Serializable && !skipSerializedCanonicalTests() && isTestSerialization()) { // Map map2 = (Map) readExternalFormFromDisk(getCanonicalEmptyCollectionName(map)); // assertEquals("Map is empty", 0, map2.size()); //} } /** * Compare the current serialized form of the Map * against the canonical version in CVS. */ public void testFullMapCompatibility() throws Exception { /** * Create canonical objects with this code Map map = makeFullMap(); if (!(map instanceof Serializable)) return; writeExternalFormToDisk((Serializable) map, getCanonicalFullCollectionName(map)); */ // test to make sure the canonical form has been preserved // GenericsNote: Serialized compatibility with older class versions is not supported for now //Map map = makeFullMap(); //if (map instanceof Serializable && !skipSerializedCanonicalTests() && isTestSerialization()) { // Map map2 = (Map) readExternalFormFromDisk(getCanonicalFullCollectionName(map)); // assertEquals("Map is the right size", getSampleKeys().length, map2.size()); //} } /** * Tests Map.put(Object, Object) */ public void testMapPut() { resetEmpty(); Object[] keys = getSampleKeys(); Object[] values = getSampleValues(); Object[] newValues = getNewSampleValues(); if (isPutAddSupported()) { for (int i = 0; i < keys.length; i++) { Object o = map.put(keys[i], values[i]); confirmed.put(keys[i], values[i]); verify(); assertTrue("First map.put should return null", o == null); assertTrue("Map should contain key after put", map.containsKey(keys[i])); assertTrue("Map should contain value after put", map.containsValue(values[i])); } if (isPutChangeSupported()) { for (int i = 0; i < keys.length; i++) { Object o = map.put(keys[i], newValues[i]); confirmed.put(keys[i], newValues[i]); verify(); assertEquals("Map.put should return previous value when changed", values[i], o); assertTrue("Map should still contain key after put when changed", map.containsKey(keys[i])); assertTrue("Map should contain new value after put when changed", map.containsValue(newValues[i])); // if duplicates are allowed, we're not guaranteed that the value // no longer exists, so don't try checking that. if (!isAllowDuplicateValues()) { assertTrue("Map should not contain old value after put when changed", !map.containsValue(values[i])); } } } else { try { // two possible exception here, either valid map.put(keys[0], newValues[0]); fail("Expected IllegalArgumentException or UnsupportedOperationException on put (change)"); } catch (IllegalArgumentException ex) { } catch (UnsupportedOperationException ex) { } } } else if (isPutChangeSupported()) { resetEmpty(); try { map.put(keys[0], values[0]); fail("Expected UnsupportedOperationException or IllegalArgumentException on put (add) when fixed size"); } catch (IllegalArgumentException ex) { } catch (UnsupportedOperationException ex) { } resetFull(); int i = 0; for (Iterator it = map.keySet().iterator(); it.hasNext() && i < newValues.length; i++) { Object key = it.next(); Object o = map.put(key, newValues[i]); Object value = confirmed.put(key, newValues[i]); verify(); assertEquals("Map.put should return previous value when changed", value, o); assertTrue("Map should still contain key after put when changed", map.containsKey(key)); assertTrue("Map should contain new value after put when changed", map.containsValue(newValues[i])); // if duplicates are allowed, we're not guaranteed that the value // no longer exists, so don't try checking that. if (!isAllowDuplicateValues()) { assertTrue("Map should not contain old value after put when changed", !map.containsValue(values[i])); } } } else { try { map.put(keys[0], values[0]); fail("Expected UnsupportedOperationException on put (add)"); } catch (UnsupportedOperationException ex) { } } } /** * Tests Map.put(null, value) */ public void testMapPutNullKey() { resetFull(); Object[] values = getSampleValues(); if (isPutAddSupported()) { if (isAllowNullKey()) { map.put(null, values[0]); } else { try { map.put(null, values[0]); fail("put(null, value) should throw NPE/IAE"); } catch (NullPointerException ex) { } catch (IllegalArgumentException ex) { } } } } /** * Tests Map.put(null, value) */ public void testMapPutNullValue() { resetFull(); Object[] keys = getSampleKeys(); if (isPutAddSupported()) { if (isAllowNullValue()) { map.put(keys[0], null); } else { try { map.put(keys[0], null); fail("put(key, null) should throw NPE/IAE"); } catch (NullPointerException ex) { } catch (IllegalArgumentException ex) { } } } } /** * Tests Map.putAll(map) */ public void testMapPutAll() { if (!isPutAddSupported()) { if (!isPutChangeSupported()) { Map temp = makeFullMap(); resetEmpty(); try { map.putAll(temp); fail("Expected UnsupportedOperationException on putAll"); } catch (UnsupportedOperationException ex) { } } return; } resetEmpty(); Map m2 = makeFullMap(); map.putAll(m2); confirmed.putAll(m2); verify(); resetEmpty(); m2 = makeConfirmedMap(); Object[] keys = getSampleKeys(); Object[] values = getSampleValues(); for (int i = 0; i < keys.length; i++) { m2.put(keys[i], values[i]); } map.putAll(m2); confirmed.putAll(m2); verify(); } /** * Tests Map.remove(Object) */ public void testMapRemove() { if (!isRemoveSupported()) { try { resetFull(); map.remove(map.keySet().iterator().next()); fail("Expected UnsupportedOperationException on remove"); } catch (UnsupportedOperationException ex) { } return; } resetEmpty(); Object[] keys = getSampleKeys(); Object[] values = getSampleValues(); for (int i = 0; i < keys.length; i++) { Object o = map.remove(keys[i]); assertTrue("First map.remove should return null", o == null); } verify(); resetFull(); for (int i = 0; i < keys.length; i++) { Object o = map.remove(keys[i]); confirmed.remove(keys[i]); verify(); assertEquals("map.remove with valid key should return value", values[i], o); } Object[] other = getOtherKeys(); resetFull(); int size = map.size(); for (int i = 0; i < other.length; i++) { Object o = map.remove(other[i]); assertEquals("map.remove for nonexistent key should return null", o, null); assertEquals("map.remove for nonexistent key should not " + "shrink map", size, map.size()); } verify(); } //----------------------------------------------------------------------- /** * Tests that the {@link Map#values} collection is backed by * the underlying map for clear(). */ public void testValuesClearChangesMap() { if (!isRemoveSupported()) return; // clear values, reflected in map resetFull(); Collection values = map.values(); assertTrue(map.size() > 0); assertTrue(values.size() > 0); values.clear(); assertTrue(map.size() == 0); assertTrue(values.size() == 0); // clear map, reflected in values resetFull(); values = map.values(); assertTrue(map.size() > 0); assertTrue(values.size() > 0); map.clear(); assertTrue(map.size() == 0); assertTrue(values.size() == 0); } /** * Tests that the {@link Map#keySet} collection is backed by * the underlying map for clear(). */ public void testKeySetClearChangesMap() { if (!isRemoveSupported()) return; // clear values, reflected in map resetFull(); Set keySet = map.keySet(); assertTrue(map.size() > 0); assertTrue(keySet.size() > 0); keySet.clear(); assertTrue(map.size() == 0); assertTrue(keySet.size() == 0); // clear map, reflected in values resetFull(); keySet = map.keySet(); assertTrue(map.size() > 0); assertTrue(keySet.size() > 0); map.clear(); assertTrue(map.size() == 0); assertTrue(keySet.size() == 0); } /** * Tests that the {@link Map#entrySet()} collection is backed by * the underlying map for clear(). */ public void testEntrySetClearChangesMap() { if (!isRemoveSupported()) return; // clear values, reflected in map resetFull(); Set entrySet = map.entrySet(); assertTrue(map.size() > 0); assertTrue(entrySet.size() > 0); entrySet.clear(); assertTrue(map.size() == 0); assertTrue(entrySet.size() == 0); // clear map, reflected in values resetFull(); entrySet = map.entrySet(); assertTrue(map.size() > 0); assertTrue(entrySet.size() > 0); map.clear(); assertTrue(map.size() == 0); assertTrue(entrySet.size() == 0); } //----------------------------------------------------------------------- public void testEntrySetContains1() { resetFull(); Set entrySet = map.entrySet(); Map.Entry entry = (Map.Entry) entrySet.iterator().next(); assertEquals(true, entrySet.contains(entry)); } public void testEntrySetContains2() { resetFull(); Set entrySet = map.entrySet(); Map.Entry entry = (Map.Entry) entrySet.iterator().next(); Map.Entry test = cloneMapEntry(entry); assertEquals(true, entrySet.contains(test)); } public void testEntrySetContains3() { resetFull(); Set entrySet = map.entrySet(); Map.Entry entry = (Map.Entry) entrySet.iterator().next(); HashMap temp = new HashMap(); temp.put(entry.getKey(), "A VERY DIFFERENT VALUE"); Map.Entry test = (Map.Entry) temp.entrySet().iterator().next(); assertEquals(false, entrySet.contains(test)); } public void testEntrySetRemove1() { if (!isRemoveSupported()) return; resetFull(); int size = map.size(); Set entrySet = map.entrySet(); Map.Entry entry = (Map.Entry) entrySet.iterator().next(); Object key = entry.getKey(); assertEquals(true, entrySet.remove(entry)); assertEquals(false, map.containsKey(key)); assertEquals(size - 1, map.size()); } public void testEntrySetRemove2() { if (!isRemoveSupported()) return; resetFull(); int size = map.size(); Set entrySet = map.entrySet(); Map.Entry entry = (Map.Entry) entrySet.iterator().next(); Object key = entry.getKey(); Map.Entry test = cloneMapEntry(entry); assertEquals(true, entrySet.remove(test)); assertEquals(false, map.containsKey(key)); assertEquals(size - 1, map.size()); } public void testEntrySetRemove3() { if (!isRemoveSupported()) return; resetFull(); int size = map.size(); Set entrySet = map.entrySet(); Map.Entry entry = (Map.Entry) entrySet.iterator().next(); Object key = entry.getKey(); HashMap temp = new HashMap(); temp.put(entry.getKey(), "A VERY DIFFERENT VALUE"); Map.Entry test = (Map.Entry) temp.entrySet().iterator().next(); assertEquals(false, entrySet.remove(test)); assertEquals(true, map.containsKey(key)); assertEquals(size, map.size()); } //----------------------------------------------------------------------- /** * Tests that the {@link Map#values} collection is backed by * the underlying map by removing from the values collection * and testing if the value was removed from the map. *

                  * We should really test the "vice versa" case--that values removed * from the map are removed from the values collection--also, * but that's a more difficult test to construct (lacking a * "removeValue" method.) *

                  *

                  * See bug * 9573. *

                  */ public void testValuesRemoveChangesMap() { resetFull(); Object[] sampleValues = getSampleValues(); Collection values = map.values(); for (int i = 0; i < sampleValues.length; i++) { if (map.containsValue(sampleValues[i])) { int j = 0; // loop counter prevents infinite loops when remove is broken while (values.contains(sampleValues[i]) && j < 10000) { try { values.remove(sampleValues[i]); } catch (UnsupportedOperationException e) { // if values.remove is unsupported, just skip this test return; } j++; } assertTrue("values().remove(obj) is broken", j < 10000); assertTrue("Value should have been removed from the underlying map.", !map.containsValue(sampleValues[i])); } } } /** * Tests that the {@link Map#keySet} set is backed by * the underlying map by removing from the keySet set * and testing if the key was removed from the map. */ public void testKeySetRemoveChangesMap() { resetFull(); Object[] sampleKeys = getSampleKeys(); Set keys = map.keySet(); for (int i = 0; i < sampleKeys.length; i++) { try { keys.remove(sampleKeys[i]); } catch (UnsupportedOperationException e) { // if key.remove is unsupported, just skip this test return; } assertTrue("Key should have been removed from the underlying map.", !map.containsKey(sampleKeys[i])); } } // TODO: Need: // testValuesRemovedFromEntrySetAreRemovedFromMap // same for EntrySet/KeySet/values's // Iterator.remove, removeAll, retainAll /** * Utility methods to create an array of Map.Entry objects * out of the given key and value arrays.

                  * * @param keys the array of keys * @param values the array of values * @return an array of Map.Entry of those keys to those values */ private Map.Entry[] makeEntryArray(Object[] keys, Object[] values) { Map.Entry[] result = new Map.Entry[keys.length]; for (int i = 0; i < keys.length; i++) { Map map = makeConfirmedMap(); map.put(keys[i], values[i]); result[i] = (Map.Entry) map.entrySet().iterator().next(); } return result; } /** * Bulk test {@link Map#entrySet()}. This method runs through all of * the tests in {@link AbstractTestSet}. * After modification operations, {@link #verify()} is invoked to ensure * that the map and the other collection views are still valid. * * @return a {@link AbstractTestSet} instance for testing the map's entry set */ public BulkTest bulkTestMapEntrySet() { return new TestMapEntrySet(); } public class TestMapEntrySet extends AbstractTestSet { public TestMapEntrySet() { super("MapEntrySet"); } // Have to implement manually; entrySet doesn't support addAll public Object[] getFullElements() { Object[] k = getSampleKeys(); Object[] v = getSampleValues(); return makeEntryArray(k, v); } // Have to implement manually; entrySet doesn't support addAll public Object[] getOtherElements() { Object[] k = getOtherKeys(); Object[] v = getOtherValues(); return makeEntryArray(k, v); } public Set makeEmptySet() { return makeEmptyMap().entrySet(); } public Set makeFullSet() { return makeFullMap().entrySet(); } public boolean isAddSupported() { // Collection views don't support add operations. return false; } public boolean isRemoveSupported() { // Entry set should only support remove if map does return AbstractTestMap.this.isRemoveSupported(); } public boolean isGetStructuralModify() { return AbstractTestMap.this.isGetStructuralModify(); } public boolean isTestSerialization() { return false; } public void resetFull() { AbstractTestMap.this.resetFull(); collection = map.entrySet(); TestMapEntrySet.this.confirmed = AbstractTestMap.this.confirmed.entrySet(); } public void resetEmpty() { AbstractTestMap.this.resetEmpty(); collection = map.entrySet(); TestMapEntrySet.this.confirmed = AbstractTestMap.this.confirmed.entrySet(); } public void testMapEntrySetIteratorEntry() { resetFull(); Iterator it = collection.iterator(); int count = 0; while (it.hasNext()) { Map.Entry entry = (Map.Entry) it.next(); assertEquals(true, AbstractTestMap.this.map.containsKey(entry.getKey())); assertEquals(true, AbstractTestMap.this.map.containsValue(entry.getValue())); if (isGetStructuralModify() == false) { assertEquals(AbstractTestMap.this.map.get(entry.getKey()), entry.getValue()); } count++; } assertEquals(collection.size(), count); } public void testMapEntrySetIteratorEntrySetValue() { Object key1 = getSampleKeys()[0]; Object key2 = (getSampleKeys().length == 1 ? getSampleKeys()[0] : getSampleKeys()[1]); Object newValue1 = getNewSampleValues()[0]; Object newValue2 = (getNewSampleValues().length == 1 ? getNewSampleValues()[0] : getNewSampleValues()[1]); resetFull(); // explicitly get entries as sample values/keys are connected for some maps // such as BeanMap Iterator it = TestMapEntrySet.this.collection.iterator(); Map.Entry entry1 = getEntry(it, key1); it = TestMapEntrySet.this.collection.iterator(); Map.Entry entry2 = getEntry(it, key2); Iterator itConfirmed = TestMapEntrySet.this.confirmed.iterator(); Map.Entry entryConfirmed1 = getEntry(itConfirmed, key1); itConfirmed = TestMapEntrySet.this.confirmed.iterator(); Map.Entry entryConfirmed2 = getEntry(itConfirmed, key2); verify(); if (isSetValueSupported() == false) { try { entry1.setValue(newValue1); } catch (UnsupportedOperationException ex) { } return; } entry1.setValue(newValue1); entryConfirmed1.setValue(newValue1); assertEquals(newValue1, entry1.getValue()); assertEquals(true, AbstractTestMap.this.map.containsKey(entry1.getKey())); assertEquals(true, AbstractTestMap.this.map.containsValue(newValue1)); assertEquals(newValue1, AbstractTestMap.this.map.get(entry1.getKey())); verify(); entry1.setValue(newValue1); entryConfirmed1.setValue(newValue1); assertEquals(newValue1, entry1.getValue()); assertEquals(true, AbstractTestMap.this.map.containsKey(entry1.getKey())); assertEquals(true, AbstractTestMap.this.map.containsValue(newValue1)); assertEquals(newValue1, AbstractTestMap.this.map.get(entry1.getKey())); verify(); entry2.setValue(newValue2); entryConfirmed2.setValue(newValue2); assertEquals(newValue2, entry2.getValue()); assertEquals(true, AbstractTestMap.this.map.containsKey(entry2.getKey())); assertEquals(true, AbstractTestMap.this.map.containsValue(newValue2)); assertEquals(newValue2, AbstractTestMap.this.map.get(entry2.getKey())); verify(); } public Map.Entry getEntry(Iterator itConfirmed, Object key) { Map.Entry entry = null; while (itConfirmed.hasNext()) { Map.Entry temp = (Map.Entry) itConfirmed.next(); if (temp.getKey() == null) { if (key == null) { entry = temp; break; } } else if (temp.getKey().equals(key)) { entry = temp; break; } } assertNotNull("No matching entry in map for key '" + key + "'", entry); return entry; } public void testMapEntrySetRemoveNonMapEntry() { if (isRemoveSupported() == false) return; resetFull(); assertEquals(false, getSet().remove(null)); assertEquals(false, getSet().remove(new Object())); } public void verify() { super.verify(); AbstractTestMap.this.verify(); } } /** * Bulk test {@link Map#keySet()}. This method runs through all of * the tests in {@link AbstractTestSet}. * After modification operations, {@link #verify()} is invoked to ensure * that the map and the other collection views are still valid. * * @return a {@link AbstractTestSet} instance for testing the map's key set */ public BulkTest bulkTestMapKeySet() { return new TestMapKeySet(); } public class TestMapKeySet extends AbstractTestSet { public TestMapKeySet() { super(""); } public Object[] getFullElements() { return getSampleKeys(); } public Object[] getOtherElements() { return getOtherKeys(); } public Set makeEmptySet() { return makeEmptyMap().keySet(); } public Set makeFullSet() { return makeFullMap().keySet(); } public boolean isNullSupported() { return AbstractTestMap.this.isAllowNullKey(); } public boolean isAddSupported() { return false; } public boolean isRemoveSupported() { return AbstractTestMap.this.isRemoveSupported(); } public boolean isTestSerialization() { return false; } public void resetEmpty() { AbstractTestMap.this.resetEmpty(); collection = map.keySet(); TestMapKeySet.this.confirmed = AbstractTestMap.this.confirmed.keySet(); } public void resetFull() { AbstractTestMap.this.resetFull(); collection = map.keySet(); TestMapKeySet.this.confirmed = AbstractTestMap.this.confirmed.keySet(); } public void verify() { super.verify(); AbstractTestMap.this.verify(); } } /** * Bulk test {@link Map#values()}. This method runs through all of * the tests in {@link AbstractTestCollection}. * After modification operations, {@link #verify()} is invoked to ensure * that the map and the other collection views are still valid. * * @return a {@link AbstractTestCollection} instance for testing the map's * values collection */ public BulkTest bulkTestMapValues() { return new TestMapValues(); } public class TestMapValues extends AbstractTestCollection { public TestMapValues() { super(""); } public Object[] getFullElements() { return getSampleValues(); } public Object[] getOtherElements() { return getOtherValues(); } public Collection makeCollection() { return makeEmptyMap().values(); } public Collection makeFullCollection() { return makeFullMap().values(); } public boolean isNullSupported() { return AbstractTestMap.this.isAllowNullKey(); } public boolean isAddSupported() { return false; } public boolean isRemoveSupported() { return AbstractTestMap.this.isRemoveSupported(); } public boolean isTestSerialization() { return false; } public boolean areEqualElementsDistinguishable() { // equal values are associated with different keys, so they are // distinguishable. return true; } public Collection makeConfirmedCollection() { // never gets called, reset methods are overridden return null; } public Collection makeConfirmedFullCollection() { // never gets called, reset methods are overridden return null; } public void resetFull() { AbstractTestMap.this.resetFull(); collection = map.values(); TestMapValues.this.confirmed = AbstractTestMap.this.confirmed.values(); } public void resetEmpty() { AbstractTestMap.this.resetEmpty(); collection = map.values(); TestMapValues.this.confirmed = AbstractTestMap.this.confirmed.values(); } public void verify() { super.verify(); AbstractTestMap.this.verify(); } // TODO: should test that a remove on the values collection view // removes the proper mapping and not just any mapping that may have // the value equal to the value returned from the values iterator. } /** * Resets the {@link #map}, {@link #entrySet}, {@link #keySet}, * {@link #values} and {@link #confirmed} fields to empty. */ public void resetEmpty() { this.map = makeEmptyMap(); views(); this.confirmed = makeConfirmedMap(); } /** * Resets the {@link #map}, {@link #entrySet}, {@link #keySet}, * {@link #values} and {@link #confirmed} fields to full. */ public void resetFull() { this.map = makeFullMap(); views(); this.confirmed = makeConfirmedMap(); Object[] k = getSampleKeys(); Object[] v = getSampleValues(); for (int i = 0; i < k.length; i++) { confirmed.put(k[i], v[i]); } } /** * Resets the collection view fields. */ private void views() { this.keySet = map.keySet(); this.values = map.values(); this.entrySet = map.entrySet(); } /** * Verifies that {@link #map} is still equal to {@link #confirmed}. * This method checks that the map is equal to the HashMap, * and that the map's collection views are still equal to * the HashMap's collection views. An equals test * is done on the maps and their collection views; their size and * isEmpty results are compared; their hashCodes are * compared; and containsAll tests are run on the * collection views. */ public void verify() { verifyMap(); verifyEntrySet(); verifyKeySet(); verifyValues(); } public void verifyMap() { int size = confirmed.size(); boolean empty = confirmed.isEmpty(); assertEquals("Map should be same size as HashMap", size, map.size()); assertEquals("Map should be empty if HashMap is", empty, map.isEmpty()); assertEquals("hashCodes should be the same", confirmed.hashCode(), map.hashCode()); // this fails for LRUMap because confirmed.equals() somehow modifies // map, causing concurrent modification exceptions. //assertEquals("Map should still equal HashMap", confirmed, map); // this works though and performs the same verification: assertTrue("Map should still equal HashMap", map.equals(confirmed)); // TODO: this should really be reexamined to figure out why LRU map // behaves like it does (the equals shouldn't modify since all accesses // by the confirmed collection should be through an iterator, thus not // causing LRUMap to change). } public void verifyEntrySet() { int size = confirmed.size(); boolean empty = confirmed.isEmpty(); assertEquals("entrySet should be same size as HashMap's" + "\nTest: " + entrySet + "\nReal: " + confirmed.entrySet(), size, entrySet.size()); assertEquals("entrySet should be empty if HashMap is" + "\nTest: " + entrySet + "\nReal: " + confirmed.entrySet(), empty, entrySet.isEmpty()); assertTrue("entrySet should contain all HashMap's elements" + "\nTest: " + entrySet + "\nReal: " + confirmed.entrySet(), entrySet.containsAll(confirmed.entrySet())); assertEquals("entrySet hashCodes should be the same" + "\nTest: " + entrySet + "\nReal: " + confirmed.entrySet(), confirmed.entrySet().hashCode(), entrySet.hashCode()); assertEquals("Map's entry set should still equal HashMap's", confirmed.entrySet(), entrySet); } public void verifyKeySet() { int size = confirmed.size(); boolean empty = confirmed.isEmpty(); assertEquals("keySet should be same size as HashMap's" + "\nTest: " + keySet + "\nReal: " + confirmed.keySet(), size, keySet.size()); assertEquals("keySet should be empty if HashMap is" + "\nTest: " + keySet + "\nReal: " + confirmed.keySet(), empty, keySet.isEmpty()); assertTrue("keySet should contain all HashMap's elements" + "\nTest: " + keySet + "\nReal: " + confirmed.keySet(), keySet.containsAll(confirmed.keySet())); assertEquals("keySet hashCodes should be the same" + "\nTest: " + keySet + "\nReal: " + confirmed.keySet(), confirmed.keySet().hashCode(), keySet.hashCode()); assertEquals("Map's key set should still equal HashMap's", confirmed.keySet(), keySet); } public void verifyValues() { List known = new ArrayList(confirmed.values()); List test = new ArrayList(values); int size = confirmed.size(); boolean empty = confirmed.isEmpty(); assertEquals("values should be same size as HashMap's" + "\nTest: " + test + "\nReal: " + known, size, values.size()); assertEquals("values should be empty if HashMap is" + "\nTest: " + test + "\nReal: " + known, empty, values.isEmpty()); assertTrue("values should contain all HashMap's elements" + "\nTest: " + test + "\nReal: " + known, test.containsAll(known)); assertTrue("values should contain all HashMap's elements" + "\nTest: " + test + "\nReal: " + known, known.containsAll(test)); // originally coded to use a HashBag, but now separate jar so... for (Iterator it = known.iterator(); it.hasNext();) { boolean removed = test.remove(it.next()); assertTrue("Map's values should still equal HashMap's", removed); } assertTrue("Map's values should still equal HashMap's", test.isEmpty()); } /** * Erases any leftover instance variables by setting them to null. */ public void tearDown() throws Exception { map = null; keySet = null; entrySet = null; values = null; confirmed = null; } } collections-generic-4.01/src/test/org/apache/commons/collections15/map/TestTransformedMap.java0000644000175000017500000001052310464140765032723 0ustar giovannigiovanni/* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.map; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.collections15.TransformerUtils; import org.apache.commons.collections15.collection.TestTransformedCollection; import java.util.HashMap; import java.util.Map; import java.util.Set; /** * Extension of {@link TestMap} for exercising the {@link TransformedMap} * implementation. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:06:04 $ * @since Commons Collections 3.0 */ public class TestTransformedMap extends AbstractTestMap { public TestTransformedMap(String testName) { super(testName); } public static Test suite() { return new TestSuite(TestTransformedMap.class); } public static void main(String args[]) { String[] testCaseName = {TestTransformedMap.class.getName()}; junit.textui.TestRunner.main(testCaseName); } //----------------------------------------------------------------------- public Map makeEmptyMap() { return TransformedMap.decorate(new HashMap(), TransformerUtils.nopTransformer(), TransformerUtils.nopTransformer()); } //----------------------------------------------------------------------- public void testTransformedMap() { Object[] els = new Object[]{"1", "3", "5", "7", "2", "4", "6"}; Map map = TransformedMap.decorate(new HashMap(), TestTransformedCollection.STRING_TO_INTEGER_TRANSFORMER, null); assertEquals(0, map.size()); for (int i = 0; i < els.length; i++) { map.put(els[i], els[i]); assertEquals(i + 1, map.size()); assertEquals(true, map.containsKey(new Integer((String) els[i]))); assertEquals(false, map.containsKey(els[i])); assertEquals(true, map.containsValue(els[i])); assertEquals(els[i], map.get(new Integer((String) els[i]))); } assertEquals(null, map.remove(els[0])); assertEquals(els[0], map.remove(new Integer((String) els[0]))); map = TransformedMap.decorate(new HashMap(), null, TestTransformedCollection.STRING_TO_INTEGER_TRANSFORMER); assertEquals(0, map.size()); for (int i = 0; i < els.length; i++) { map.put(els[i], els[i]); assertEquals(i + 1, map.size()); assertEquals(true, map.containsValue(new Integer((String) els[i]))); assertEquals(false, map.containsValue(els[i])); assertEquals(true, map.containsKey(els[i])); assertEquals(new Integer((String) els[i]), map.get(els[i])); } assertEquals(new Integer((String) els[0]), map.remove(els[0])); Set entrySet = map.entrySet(); Map.Entry[] array = (Map.Entry[]) entrySet.toArray(new Map.Entry[0]); array[0].setValue("66"); assertEquals(new Integer(66), array[0].getValue()); assertEquals(new Integer(66), map.get(array[0].getKey())); Map.Entry entry = (Map.Entry) entrySet.iterator().next(); entry.setValue("88"); assertEquals(new Integer(88), entry.getValue()); assertEquals(new Integer(88), map.get(entry.getKey())); } public String getCompatibilityVersion() { return "3.1"; } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk( // (java.io.Serializable) map, // "D:/dev/collections15/data/test/TransformedMap.emptyCollection.version3.1.obj"); // resetFull(); // writeExternalFormToDisk( // (java.io.Serializable) map, // "D:/dev/collections15/data/test/TransformedMap.fullCollection.version3.1.obj"); // } } collections-generic-4.01/src/test/org/apache/commons/collections15/map/TestPredicatedSortedMap.java0000644000175000017500000001425210464140754033665 0ustar giovannigiovanni/* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.map; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.collections15.Predicate; import org.apache.commons.collections15.PredicateUtils; import java.util.*; /** * Extension of {@link TestPredicatedMap} for exercising the * {@link PredicatedSortedMap} implementation. * * @author Matt Hall, John Watkinson, Phil Steitz * @version $Revision: 1.1 $ $Date: 2005/10/11 19:11:58 $ * @since Commons Collections 3.0 */ public class TestPredicatedSortedMap extends AbstractTestSortedMap { protected static final Predicate truePredicate = PredicateUtils.truePredicate(); protected static final Predicate testPredicate = new Predicate() { public boolean evaluate(Object o) { return (o instanceof String); } }; public TestPredicatedSortedMap(String testName) { super(testName); } public static Test suite() { return new TestSuite(TestPredicatedSortedMap.class); } public static void main(String args[]) { String[] testCaseName = {TestPredicatedSortedMap.class.getName()}; junit.textui.TestRunner.main(testCaseName); } //----------------------------------------------------------------------- protected SortedMap decorateMap(SortedMap map, Predicate keyPredicate, Predicate valuePredicate) { return PredicatedSortedMap.decorate(map, keyPredicate, valuePredicate); } public Map makeEmptyMap() { return decorateMap(new TreeMap(), truePredicate, truePredicate); } public Map makeTestMap() { return decorateMap(new TreeMap(), testPredicate, testPredicate); } public SortedMap makeTestSortedMap() { return decorateMap(new TreeMap(), testPredicate, testPredicate); } public boolean isSubMapViewsSerializable() { // TreeMap sub map views have a bug in deserialization. return false; } public boolean isAllowNullKey() { return false; } // from TestPredicatedMap //----------------------------------------------------------------------- public void testEntrySet() { SortedMap map = makeTestSortedMap(); assertTrue("returned entryset should not be null", map.entrySet() != null); map = decorateMap(new TreeMap(), null, null); map.put("oneKey", "oneValue"); assertTrue("returned entryset should contain one entry", map.entrySet().size() == 1); map = decorateMap(map, null, null); } public void testPut() { Map map = makeTestMap(); try { map.put("Hi", new Integer(3)); fail("Illegal value should raise IllegalArgument"); } catch (IllegalArgumentException e) { // expected } try { map.put(new Integer(3), "Hi"); fail("Illegal key should raise IllegalArgument"); } catch (IllegalArgumentException e) { // expected } assertTrue(!map.containsKey(new Integer(3))); assertTrue(!map.containsValue(new Integer(3))); Map map2 = new HashMap(); map2.put("A", "a"); map2.put("B", "b"); map2.put("C", "c"); map2.put("c", new Integer(3)); try { map.putAll(map2); fail("Illegal value should raise IllegalArgument"); } catch (IllegalArgumentException e) { // expected } map.put("E", "e"); Iterator iterator = map.entrySet().iterator(); try { Map.Entry entry = (Map.Entry) iterator.next(); entry.setValue(new Integer(3)); fail("Illegal value should raise IllegalArgument"); } catch (IllegalArgumentException e) { // expected } map.put("F", "f"); iterator = map.entrySet().iterator(); Map.Entry entry = (Map.Entry) iterator.next(); entry.setValue("x"); } //----------------------------------------------------------------------- public void testSortOrder() { SortedMap map = makeTestSortedMap(); map.put("A", "a"); map.put("B", "b"); try { map.put(null, "c"); fail("Null key should raise IllegalArgument"); } catch (IllegalArgumentException e) { // expected } map.put("C", "c"); try { map.put("D", null); fail("Null value should raise IllegalArgument"); } catch (IllegalArgumentException e) { // expected } assertEquals("First key should be A", map.firstKey(), "A"); assertEquals("Last key should be C", map.lastKey(), "C"); assertEquals("First key in tail map should be B", map.tailMap("B").firstKey(), "B"); assertEquals("Last key in head map should be B", map.headMap("C").lastKey(), "B"); assertEquals("Last key in submap should be B", map.subMap("A", "C").lastKey(), "B"); Comparator c = map.comparator(); assertTrue("natural order, so comparator should be null", c == null); } public String getCompatibilityVersion() { return "3.1"; } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk( // (java.io.Serializable) map, // "D:/dev/collections15/data/test/PredicatedSortedMap.emptyCollection.version3.1.obj"); // resetFull(); // writeExternalFormToDisk( // (java.io.Serializable) map, // "D:/dev/collections15/data/test/PredicatedSortedMap.fullCollection.version3.1.obj"); // } }collections-generic-4.01/src/test/org/apache/commons/collections15/map/TestHashedMap.java0000644000175000017500000000402110464140761031623 0ustar giovannigiovanni/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.map; import junit.framework.Test; import junit.textui.TestRunner; import org.apache.commons.collections15.BulkTest; import java.util.Map; /** * JUnit tests. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 19:11:58 $ */ public class TestHashedMap extends AbstractTestIterableMap { public TestHashedMap(String testName) { super(testName); } public static void main(String[] args) { TestRunner.run(suite()); } public static Test suite() { return BulkTest.makeSuite(TestHashedMap.class); } public Map makeEmptyMap() { return new HashedMap(); } public String getCompatibilityVersion() { return "3"; } public void testClone() { HashedMap map = new HashedMap(10); map.put("1", "1"); Map cloned = (Map) map.clone(); assertEquals(map.size(), cloned.size()); assertSame(map.get("1"), cloned.get("1")); } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk((java.io.Serializable) map, "D:/dev/collections15/data/test/HashedMap.emptyCollection.version3.obj"); // resetFull(); // writeExternalFormToDisk((java.io.Serializable) map, "D:/dev/collections15/data/test/HashedMap.fullCollection.version3.obj"); // } } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootcollections-generic-4.01/src/test/org/apache/commons/collections15/map/TestUnmodifiableOrderedMap.javacollections-generic-4.01/src/test/org/apache/commons/collections15/map/TestUnmodifiableOrderedMap.ja0000644000175000017500000000642210464140760034011 0ustar giovannigiovanni/* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.map; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.collections15.OrderedMap; import org.apache.commons.collections15.Unmodifiable; import java.util.HashMap; import java.util.Map; /** * Extension of {@link AbstractTestOrderedMap} for exercising the * {@link UnmodifiableOrderedMap} implementation. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:06:04 $ * @since Commons Collections 3.0 */ public class TestUnmodifiableOrderedMap extends AbstractTestOrderedMap { public TestUnmodifiableOrderedMap(String testName) { super(testName); } public static Test suite() { return new TestSuite(TestUnmodifiableOrderedMap.class); } public static void main(String args[]) { String[] testCaseName = {TestUnmodifiableOrderedMap.class.getName()}; junit.textui.TestRunner.main(testCaseName); } //------------------------------------------------------------------- public Map makeEmptyMap() { return UnmodifiableOrderedMap.decorate(ListOrderedMap.decorate(new HashMap())); } public boolean isPutChangeSupported() { return false; } public boolean isPutAddSupported() { return false; } public boolean isRemoveSupported() { return false; } public Map makeFullMap() { OrderedMap m = ListOrderedMap.decorate(new HashMap()); addSampleMappings(m); return UnmodifiableOrderedMap.decorate(m); } //----------------------------------------------------------------------- public void testUnmodifiable() { assertTrue(makeEmptyMap() instanceof Unmodifiable); assertTrue(makeFullMap() instanceof Unmodifiable); } public void testDecorateFactory() { Map map = makeFullMap(); assertSame(map, UnmodifiableOrderedMap.decorate((OrderedMap) map)); try { UnmodifiableOrderedMap.decorate(null); fail(); } catch (IllegalArgumentException ex) { } } public String getCompatibilityVersion() { return "3.1"; } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk( // (java.io.Serializable) map, // "D:/dev/collections15/data/test/UnmodifiableOrderedMap.emptyCollection.version3.1.obj"); // resetFull(); // writeExternalFormToDisk( // (java.io.Serializable) map, // "D:/dev/collections15/data/test/UnmodifiableOrderedMap.fullCollection.version3.1.obj"); // } }collections-generic-4.01/src/test/org/apache/commons/collections15/map/TestLRUMap.java0000644000175000017500000002576310464140764031114 0ustar giovannigiovanni/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.map; import junit.framework.Test; import junit.textui.TestRunner; import org.apache.commons.collections15.BulkTest; import org.apache.commons.collections15.OrderedMap; import org.apache.commons.collections15.ResettableIterator; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; /** * JUnit tests. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 19:11:58 $ */ public class TestLRUMap extends AbstractTestOrderedMap { public TestLRUMap(String testName) { super(testName); } public static void main(String[] args) { TestRunner.run(suite()); } public static Test suite() { return BulkTest.makeSuite(TestLRUMap.class); } public Map makeEmptyMap() { return new LRUMap(); } public boolean isGetStructuralModify() { return true; } public String getCompatibilityVersion() { return "3"; } //----------------------------------------------------------------------- public void testLRU() { if (isPutAddSupported() == false || isPutChangeSupported() == false) return; Object[] keys = getSampleKeys(); Object[] values = getSampleValues(); Iterator it = null; LRUMap map = new LRUMap(2); assertEquals(0, map.size()); assertEquals(false, map.isFull()); assertEquals(2, map.maxSize()); map.put(keys[0], values[0]); assertEquals(1, map.size()); assertEquals(false, map.isFull()); assertEquals(2, map.maxSize()); map.put(keys[1], values[1]); assertEquals(2, map.size()); assertEquals(true, map.isFull()); assertEquals(2, map.maxSize()); it = map.keySet().iterator(); assertSame(keys[0], it.next()); assertSame(keys[1], it.next()); it = map.values().iterator(); assertSame(values[0], it.next()); assertSame(values[1], it.next()); map.put(keys[2], values[2]); assertEquals(2, map.size()); assertEquals(true, map.isFull()); assertEquals(2, map.maxSize()); it = map.keySet().iterator(); assertSame(keys[1], it.next()); assertSame(keys[2], it.next()); it = map.values().iterator(); assertSame(values[1], it.next()); assertSame(values[2], it.next()); map.put(keys[2], values[0]); assertEquals(2, map.size()); assertEquals(true, map.isFull()); assertEquals(2, map.maxSize()); it = map.keySet().iterator(); assertSame(keys[1], it.next()); assertSame(keys[2], it.next()); it = map.values().iterator(); assertSame(values[1], it.next()); assertSame(values[0], it.next()); map.put(keys[1], values[3]); assertEquals(2, map.size()); assertEquals(true, map.isFull()); assertEquals(2, map.maxSize()); it = map.keySet().iterator(); assertSame(keys[2], it.next()); assertSame(keys[1], it.next()); it = map.values().iterator(); assertSame(values[0], it.next()); assertSame(values[3], it.next()); } //----------------------------------------------------------------------- public void testReset() { resetEmpty(); OrderedMap ordered = (OrderedMap) map; ((ResettableIterator) ordered.mapIterator()).reset(); resetFull(); ordered = (OrderedMap) map; List list = new ArrayList(ordered.keySet()); ResettableIterator it = (ResettableIterator) ordered.mapIterator(); assertSame(list.get(0), it.next()); assertSame(list.get(1), it.next()); it.reset(); assertSame(list.get(0), it.next()); } //----------------------------------------------------------------------- public void testAccessOrder() { if (isPutAddSupported() == false || isPutChangeSupported() == false) return; Object[] keys = getSampleKeys(); Object[] values = getSampleValues(); Iterator it = null; resetEmpty(); map.put(keys[0], values[0]); map.put(keys[1], values[1]); it = map.keySet().iterator(); assertSame(keys[0], it.next()); assertSame(keys[1], it.next()); it = map.values().iterator(); assertSame(values[0], it.next()); assertSame(values[1], it.next()); // no change to order map.put(keys[1], values[1]); it = map.keySet().iterator(); assertSame(keys[0], it.next()); assertSame(keys[1], it.next()); it = map.values().iterator(); assertSame(values[0], it.next()); assertSame(values[1], it.next()); // no change to order map.put(keys[1], values[2]); it = map.keySet().iterator(); assertSame(keys[0], it.next()); assertSame(keys[1], it.next()); it = map.values().iterator(); assertSame(values[0], it.next()); assertSame(values[2], it.next()); // change to order map.put(keys[0], values[3]); it = map.keySet().iterator(); assertSame(keys[1], it.next()); assertSame(keys[0], it.next()); it = map.values().iterator(); assertSame(values[2], it.next()); assertSame(values[3], it.next()); // change to order map.get(keys[1]); it = map.keySet().iterator(); assertSame(keys[0], it.next()); assertSame(keys[1], it.next()); it = map.values().iterator(); assertSame(values[3], it.next()); assertSame(values[2], it.next()); // change to order map.get(keys[0]); it = map.keySet().iterator(); assertSame(keys[1], it.next()); assertSame(keys[0], it.next()); it = map.values().iterator(); assertSame(values[2], it.next()); assertSame(values[3], it.next()); // no change to order map.get(keys[0]); it = map.keySet().iterator(); assertSame(keys[1], it.next()); assertSame(keys[0], it.next()); it = map.values().iterator(); assertSame(values[2], it.next()); assertSame(values[3], it.next()); } public void testClone() { LRUMap map = new LRUMap(10); map.put("1", "1"); Map cloned = (Map) map.clone(); assertEquals(map.size(), cloned.size()); assertSame(map.get("1"), cloned.get("1")); } public void testRemoveLRU() { MockLRUMapSubclass map = new MockLRUMapSubclass(2); assertNull(map.entry); map.put("A", "a"); assertNull(map.entry); map.put("B", "b"); assertNull(map.entry); map.put("C", "c"); // removes oldest, which is A=a assertNotNull(map.entry); assertEquals("A", map.key); assertEquals("a", map.value); assertEquals("C", map.entry.getKey()); // entry is reused assertEquals("c", map.entry.getValue()); // entry is reused assertEquals(false, map.containsKey("A")); assertEquals(true, map.containsKey("B")); assertEquals(true, map.containsKey("C")); } static class MockLRUMapSubclass extends LRUMap { LinkEntry entry; Object key; Object value; MockLRUMapSubclass(int size) { super(size); } protected boolean removeLRU(LinkEntry entry) { this.entry = entry; this.key = entry.getKey(); this.value = entry.getValue(); return true; } } public void testRemoveLRUBlocksRemove() { MockLRUMapSubclassBlocksRemove map = new MockLRUMapSubclassBlocksRemove(2, false); assertEquals(0, map.size()); map.put("A", "a"); assertEquals(1, map.size()); map.put("B", "b"); assertEquals(2, map.size()); map.put("C", "c"); // should remove oldest, which is A=a, but this is blocked assertEquals(3, map.size()); assertEquals(2, map.maxSize()); assertEquals(true, map.containsKey("A")); assertEquals(true, map.containsKey("B")); assertEquals(true, map.containsKey("C")); } public void testRemoveLRUBlocksRemoveScan() { MockLRUMapSubclassBlocksRemove map = new MockLRUMapSubclassBlocksRemove(2, true); assertEquals(0, map.size()); map.put("A", "a"); assertEquals(1, map.size()); map.put("B", "b"); assertEquals(2, map.size()); map.put("C", "c"); // should remove oldest, which is A=a, but this is blocked assertEquals(3, map.size()); assertEquals(2, map.maxSize()); assertEquals(true, map.containsKey("A")); assertEquals(true, map.containsKey("B")); assertEquals(true, map.containsKey("C")); } static class MockLRUMapSubclassBlocksRemove extends LRUMap { MockLRUMapSubclassBlocksRemove(int size, boolean scanUntilRemove) { super(size, scanUntilRemove); } protected boolean removeLRU(LinkEntry entry) { return false; } } public void testRemoveLRUFirstBlocksRemove() { MockLRUMapSubclassFirstBlocksRemove map = new MockLRUMapSubclassFirstBlocksRemove(2); assertEquals(0, map.size()); map.put("A", "a"); assertEquals(1, map.size()); map.put("B", "b"); assertEquals(2, map.size()); map.put("C", "c"); // should remove oldest, which is A=a but this is blocked - so advance to B=b assertEquals(2, map.size()); assertEquals(2, map.maxSize()); assertEquals(true, map.containsKey("A")); assertEquals(false, map.containsKey("B")); assertEquals(true, map.containsKey("C")); } static class MockLRUMapSubclassFirstBlocksRemove extends LRUMap { MockLRUMapSubclassFirstBlocksRemove(int size) { super(size, true); } protected boolean removeLRU(LinkEntry entry) { if ("a".equals(entry.getValue())) { return false; } else { return true; } } } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk((java.io.Serializable) map, "D:/dev/collections15/data/test/LRUMap.emptyCollection.version3.obj"); // resetFull(); // writeExternalFormToDisk((java.io.Serializable) map, "D:/dev/collections15/data/test/LRUMap.fullCollection.version3.obj"); // } } collections-generic-4.01/src/test/org/apache/commons/collections15/map/TestListOrderedMap.java0000644000175000017500000001444010464140756032661 0ustar giovannigiovanni/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.map; import junit.framework.Test; import org.apache.commons.collections15.BulkTest; import org.apache.commons.collections15.MapIterator; import org.apache.commons.collections15.list.AbstractTestList; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Extension of {@link TestMap} for exercising the {@link ListOrderedMap} * implementation. * * @author Henri Yandell * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 19:11:58 $ * @since Commons Collections 3.0 */ public class TestListOrderedMap extends AbstractTestOrderedMap { public TestListOrderedMap(String testName) { super(testName); } public static Test suite() { return BulkTest.makeSuite(TestListOrderedMap.class); } public static void main(String args[]) { String[] testCaseName = {TestListOrderedMap.class.getName()}; junit.textui.TestRunner.main(testCaseName); } public Map makeEmptyMap() { return ListOrderedMap.decorate(new HashMap()); } //----------------------------------------------------------------------- public void testGetByIndex() { resetEmpty(); ListOrderedMap lom = (ListOrderedMap) map; try { lom.get(0); } catch (IndexOutOfBoundsException ex) { } try { lom.get(-1); } catch (IndexOutOfBoundsException ex) { } resetFull(); lom = (ListOrderedMap) map; try { lom.get(-1); } catch (IndexOutOfBoundsException ex) { } try { lom.get(lom.size()); } catch (IndexOutOfBoundsException ex) { } int i = 0; for (MapIterator it = lom.mapIterator(); it.hasNext(); i++) { assertSame(it.next(), lom.get(i)); } } public void testGetValueByIndex() { resetEmpty(); ListOrderedMap lom = (ListOrderedMap) map; try { lom.getValue(0); } catch (IndexOutOfBoundsException ex) { } try { lom.getValue(-1); } catch (IndexOutOfBoundsException ex) { } resetFull(); lom = (ListOrderedMap) map; try { lom.getValue(-1); } catch (IndexOutOfBoundsException ex) { } try { lom.getValue(lom.size()); } catch (IndexOutOfBoundsException ex) { } int i = 0; for (MapIterator it = lom.mapIterator(); it.hasNext(); i++) { it.next(); assertSame(it.getValue(), lom.getValue(i)); } } public void testIndexOf() { resetEmpty(); ListOrderedMap lom = (ListOrderedMap) map; assertEquals(-1, lom.indexOf(getOtherKeys())); resetFull(); lom = (ListOrderedMap) map; List list = new ArrayList(); for (MapIterator it = lom.mapIterator(); it.hasNext();) { list.add(it.next()); } for (int i = 0; i < list.size(); i++) { assertEquals(i, lom.indexOf(list.get(i))); } } public void testRemoveByIndex() { resetEmpty(); ListOrderedMap lom = (ListOrderedMap) map; try { lom.remove(0); } catch (IndexOutOfBoundsException ex) { } try { lom.remove(-1); } catch (IndexOutOfBoundsException ex) { } resetFull(); lom = (ListOrderedMap) map; try { lom.remove(-1); } catch (IndexOutOfBoundsException ex) { } try { lom.remove(lom.size()); } catch (IndexOutOfBoundsException ex) { } List list = new ArrayList(); for (MapIterator it = lom.mapIterator(); it.hasNext();) { list.add(it.next()); } for (int i = 0; i < list.size(); i++) { Object key = list.get(i); Object value = lom.get(key); assertEquals(value, lom.remove(i)); list.remove(i); assertEquals(false, lom.containsKey(key)); } } public BulkTest bulkTestListView() { return new TestListView(); } public class TestListView extends AbstractTestList { TestListView() { super("TestListView"); } public List makeEmptyList() { return ((ListOrderedMap) TestListOrderedMap.this.makeEmptyMap()).asList(); } public List makeFullList() { return ((ListOrderedMap) TestListOrderedMap.this.makeFullMap()).asList(); } public Object[] getFullElements() { return TestListOrderedMap.this.getSampleKeys(); } public boolean isAddSupported() { return false; } public boolean isRemoveSupported() { return false; } public boolean isSetSupported() { return false; } public boolean isNullSupported() { return TestListOrderedMap.this.isAllowNullKey(); } public boolean isTestSerialization() { return false; } } public String getCompatibilityVersion() { return "3.1"; } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk( // (java.io.Serializable) map, // "D:/dev/collections15/data/test/ListOrderedMap.emptyCollection.version3.1.obj"); // resetFull(); // writeExternalFormToDisk( // (java.io.Serializable) map, // "D:/dev/collections15/data/test/ListOrderedMap.fullCollection.version3.1.obj"); // } } collections-generic-4.01/src/test/org/apache/commons/collections15/map/AbstractTestSortedMap.java0000644000175000017500000003140410464140762033361 0ustar giovannigiovanni/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.map; import org.apache.commons.collections15.BulkTest; import java.util.*; /** * Abstract test class for {@link java.util.SortedMap} methods and contracts. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 19:11:58 $ */ public abstract class AbstractTestSortedMap extends AbstractTestMap { /** * JUnit constructor. * * @param testName the test name */ public AbstractTestSortedMap(String testName) { super(testName); } //----------------------------------------------------------------------- /** * Can't sort null keys. * * @return false */ public boolean isAllowNullKey() { return false; } /** * SortedMap uses TreeMap as its known comparison. * * @return a map that is known to be valid */ public Map makeConfirmedMap() { return new TreeMap(); } //----------------------------------------------------------------------- public void testComparator() { SortedMap sm = (SortedMap) makeFullMap(); // no tests I can think of } public void testFirstKey() { SortedMap sm = (SortedMap) makeFullMap(); assertSame(sm.keySet().iterator().next(), sm.firstKey()); } public void testLastKey() { SortedMap sm = (SortedMap) makeFullMap(); Object obj = null; for (Iterator it = sm.keySet().iterator(); it.hasNext();) { obj = (Object) it.next(); } assertSame(obj, sm.lastKey()); } //----------------------------------------------------------------------- public BulkTest bulkTestHeadMap() { return new TestHeadMap(this); } public BulkTest bulkTestTailMap() { return new TestTailMap(this); } public BulkTest bulkTestSubMap() { return new TestSubMap(this); } public static abstract class TestViewMap extends AbstractTestSortedMap { protected final AbstractTestMap main; protected final List subSortedKeys = new ArrayList(); protected final List subSortedValues = new ArrayList(); protected final List subSortedNewValues = new ArrayList(); public TestViewMap(String name, AbstractTestMap main) { super(name); this.main = main; } public void resetEmpty() { // needed to init verify correctly main.resetEmpty(); super.resetEmpty(); } public void resetFull() { // needed to init verify correctly main.resetFull(); super.resetFull(); } public void verify() { // cross verify changes on view with changes on main map super.verify(); main.verify(); } public BulkTest bulkTestHeadMap() { return null; // block infinite recursion } public BulkTest bulkTestTailMap() { return null; // block infinite recursion } public BulkTest bulkTestSubMap() { return null; // block infinite recursion } public Object[] getSampleKeys() { return subSortedKeys.toArray(); } public Object[] getSampleValues() { return subSortedValues.toArray(); } public Object[] getNewSampleValues() { return subSortedNewValues.toArray(); } public boolean isAllowNullKey() { return main.isAllowNullKey(); } public boolean isAllowNullValue() { return main.isAllowNullValue(); } public boolean isPutAddSupported() { return main.isPutAddSupported(); } public boolean isPutChangeSupported() { return main.isPutChangeSupported(); } public boolean isRemoveSupported() { return main.isRemoveSupported(); } public boolean isTestSerialization() { return false; } // public void testSimpleSerialization() throws Exception { // if (main.isSubMapViewsSerializable() == false) return; // super.testSimpleSerialization(); // } // public void testSerializeDeserializeThenCompare() throws Exception { // if (main.isSubMapViewsSerializable() == false) return; // super.testSerializeDeserializeThenCompare(); // } // public void testEmptyMapCompatibility() throws Exception { // if (main.isSubMapViewsSerializable() == false) return; // super.testEmptyMapCompatibility(); // } // public void testFullMapCompatibility() throws Exception { // if (main.isSubMapViewsSerializable() == false) return; // super.testFullMapCompatibility(); // } } public static class TestHeadMap extends TestViewMap { static final int SUBSIZE = 6; final Object toKey; public TestHeadMap(AbstractTestMap main) { super("SortedMap.HeadMap", main); SortedMap sm = (SortedMap) main.makeFullMap(); for (Iterator it = sm.entrySet().iterator(); it.hasNext();) { Map.Entry entry = (Map.Entry) it.next(); this.subSortedKeys.add(entry.getKey()); this.subSortedValues.add(entry.getValue()); } this.toKey = this.subSortedKeys.get(SUBSIZE); this.subSortedKeys.subList(SUBSIZE, this.subSortedKeys.size()).clear(); this.subSortedValues.subList(SUBSIZE, this.subSortedValues.size()).clear(); this.subSortedNewValues.addAll(Arrays.asList(main.getNewSampleValues()).subList(0, SUBSIZE)); } public Map makeEmptyMap() { // done this way so toKey is correctly set in the returned map return ((SortedMap) main.makeEmptyMap()).headMap(toKey); } public Map makeFullMap() { return ((SortedMap) main.makeFullMap()).headMap(toKey); } public void testHeadMapOutOfRange() { if (isPutAddSupported() == false) return; resetEmpty(); try { ((SortedMap) map).put(toKey, subSortedValues.get(0)); fail(); } catch (IllegalArgumentException ex) { } verify(); } public String getCompatibilityVersion() { return main.getCompatibilityVersion() + ".HeadMapView"; } // public void testCreate() throws Exception { // Map map = makeEmptyMap(); // writeExternalFormToDisk( // (java.io.Serializable) map, // "D:/dev/collections15/data/test/FixedSizeSortedMap.emptyCollection.version3.1.HeadMapView.obj"); // map = makeFullMap(); // writeExternalFormToDisk( // (java.io.Serializable) map, // "D:/dev/collections15/data/test/FixedSizeSortedMap.fullCollection.version3.1.HeadMapView.obj"); // } } public static class TestTailMap extends TestViewMap { static final int SUBSIZE = 6; final Object fromKey; final Object invalidKey; public TestTailMap(AbstractTestMap main) { super("SortedMap.TailMap", main); SortedMap sm = (SortedMap) main.makeFullMap(); for (Iterator it = sm.entrySet().iterator(); it.hasNext();) { Map.Entry entry = (Map.Entry) it.next(); this.subSortedKeys.add(entry.getKey()); this.subSortedValues.add(entry.getValue()); } this.fromKey = this.subSortedKeys.get(this.subSortedKeys.size() - SUBSIZE); this.invalidKey = this.subSortedKeys.get(this.subSortedKeys.size() - SUBSIZE - 1); this.subSortedKeys.subList(0, this.subSortedKeys.size() - SUBSIZE).clear(); this.subSortedValues.subList(0, this.subSortedValues.size() - SUBSIZE).clear(); this.subSortedNewValues.addAll(Arrays.asList(main.getNewSampleValues()).subList(0, SUBSIZE)); } public Map makeEmptyMap() { // done this way so toKey is correctly set in the returned map return ((SortedMap) main.makeEmptyMap()).tailMap(fromKey); } public Map makeFullMap() { return ((SortedMap) main.makeFullMap()).tailMap(fromKey); } public void testTailMapOutOfRange() { if (isPutAddSupported() == false) return; resetEmpty(); try { ((SortedMap) map).put(invalidKey, subSortedValues.get(0)); fail(); } catch (IllegalArgumentException ex) { } verify(); } public String getCompatibilityVersion() { return main.getCompatibilityVersion() + ".TailMapView"; } // public void testCreate() throws Exception { // Map map = makeEmptyMap(); // writeExternalFormToDisk( // (java.io.Serializable) map, // "D:/dev/collections15/data/test/FixedSizeSortedMap.emptyCollection.version3.1.TailMapView.obj"); // map = makeFullMap(); // writeExternalFormToDisk( // (java.io.Serializable) map, // "D:/dev/collections15/data/test/FixedSizeSortedMap.fullCollection.version3.1.TailMapView.obj"); // } } public static class TestSubMap extends TestViewMap { static final int SUBSIZE = 3; final Object fromKey; final Object toKey; public TestSubMap(AbstractTestMap main) { super("SortedMap.SubMap", main); SortedMap sm = (SortedMap) main.makeFullMap(); for (Iterator it = sm.entrySet().iterator(); it.hasNext();) { Map.Entry entry = (Map.Entry) it.next(); this.subSortedKeys.add(entry.getKey()); this.subSortedValues.add(entry.getValue()); } this.fromKey = this.subSortedKeys.get(SUBSIZE); this.toKey = this.subSortedKeys.get(this.subSortedKeys.size() - SUBSIZE); this.subSortedKeys.subList(0, SUBSIZE).clear(); this.subSortedKeys.subList(this.subSortedKeys.size() - SUBSIZE, this.subSortedKeys.size()).clear(); this.subSortedValues.subList(0, SUBSIZE).clear(); this.subSortedValues.subList(this.subSortedValues.size() - SUBSIZE, this.subSortedValues.size()).clear(); this.subSortedNewValues.addAll(Arrays.asList(main.getNewSampleValues()).subList(SUBSIZE, this.main.getNewSampleValues().length - SUBSIZE)); } public Map makeEmptyMap() { // done this way so toKey is correctly set in the returned map return ((SortedMap) main.makeEmptyMap()).subMap(fromKey, toKey); } public Map makeFullMap() { return ((SortedMap) main.makeFullMap()).subMap(fromKey, toKey); } public void testSubMapOutOfRange() { if (isPutAddSupported() == false) return; resetEmpty(); try { ((SortedMap) map).put(toKey, subSortedValues.get(0)); fail(); } catch (IllegalArgumentException ex) { } verify(); } public String getCompatibilityVersion() { return main.getCompatibilityVersion() + ".SubMapView"; } // public void testCreate() throws Exception { // Map map = makeEmptyMap(); // writeExternalFormToDisk( // (java.io.Serializable) map, // "D:/dev/collections15/data/test/TransformedSortedMap.emptyCollection.version3.1.SubMapView.obj"); // map = makeFullMap(); // writeExternalFormToDisk( // (java.io.Serializable) map, // "D:/dev/collections15/data/test/TransformedSortedMap.fullCollection.version3.1.SubMapView.obj"); // } } } collections-generic-4.01/src/test/org/apache/commons/collections15/map/TestLinkedMap.java0000644000175000017500000002051010464140761031636 0ustar giovannigiovanni/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.map; import junit.framework.Test; import junit.textui.TestRunner; import org.apache.commons.collections15.BulkTest; import org.apache.commons.collections15.MapIterator; import org.apache.commons.collections15.OrderedMap; import org.apache.commons.collections15.ResettableIterator; import org.apache.commons.collections15.list.AbstractTestList; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; /** * JUnit tests. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 19:11:58 $ */ public class TestLinkedMap extends AbstractTestOrderedMap { public TestLinkedMap(String testName) { super(testName); } public static void main(String[] args) { TestRunner.run(suite()); } public static Test suite() { return BulkTest.makeSuite(TestLinkedMap.class); } public Map makeEmptyMap() { return new LinkedMap(); } public String getCompatibilityVersion() { return "3"; } //----------------------------------------------------------------------- public void testReset() { resetEmpty(); OrderedMap ordered = (OrderedMap) map; ((ResettableIterator) ordered.mapIterator()).reset(); resetFull(); ordered = (OrderedMap) map; List list = new ArrayList(ordered.keySet()); ResettableIterator it = (ResettableIterator) ordered.mapIterator(); assertSame(list.get(0), it.next()); assertSame(list.get(1), it.next()); it.reset(); assertSame(list.get(0), it.next()); } //----------------------------------------------------------------------- public void testInsertionOrder() { if (isPutAddSupported() == false || isPutChangeSupported() == false) return; Object[] keys = getSampleKeys(); Object[] values = getSampleValues(); Iterator it = null; resetEmpty(); map.put(keys[0], values[0]); map.put(keys[1], values[1]); it = map.keySet().iterator(); assertSame(keys[0], it.next()); assertSame(keys[1], it.next()); it = map.values().iterator(); assertSame(values[0], it.next()); assertSame(values[1], it.next()); // no change to order map.put(keys[1], values[1]); it = map.keySet().iterator(); assertSame(keys[0], it.next()); assertSame(keys[1], it.next()); it = map.values().iterator(); assertSame(values[0], it.next()); assertSame(values[1], it.next()); // no change to order map.put(keys[1], values[2]); it = map.keySet().iterator(); assertSame(keys[0], it.next()); assertSame(keys[1], it.next()); it = map.values().iterator(); assertSame(values[0], it.next()); assertSame(values[2], it.next()); // no change to order map.put(keys[0], values[3]); it = map.keySet().iterator(); assertSame(keys[0], it.next()); assertSame(keys[1], it.next()); it = map.values().iterator(); assertSame(values[3], it.next()); assertSame(values[2], it.next()); } //----------------------------------------------------------------------- public void testGetByIndex() { resetEmpty(); LinkedMap lm = (LinkedMap) map; try { lm.get(0); } catch (IndexOutOfBoundsException ex) { } try { lm.get(-1); } catch (IndexOutOfBoundsException ex) { } resetFull(); lm = (LinkedMap) map; try { lm.get(-1); } catch (IndexOutOfBoundsException ex) { } try { lm.get(lm.size()); } catch (IndexOutOfBoundsException ex) { } int i = 0; for (MapIterator it = lm.mapIterator(); it.hasNext(); i++) { assertSame(it.next(), lm.get(i)); } } public void testGetValueByIndex() { resetEmpty(); LinkedMap lm = (LinkedMap) map; try { lm.getValue(0); } catch (IndexOutOfBoundsException ex) { } try { lm.getValue(-1); } catch (IndexOutOfBoundsException ex) { } resetFull(); lm = (LinkedMap) map; try { lm.getValue(-1); } catch (IndexOutOfBoundsException ex) { } try { lm.getValue(lm.size()); } catch (IndexOutOfBoundsException ex) { } int i = 0; for (MapIterator it = lm.mapIterator(); it.hasNext(); i++) { it.next(); assertSame(it.getValue(), lm.getValue(i)); } } public void testIndexOf() { resetEmpty(); LinkedMap lm = (LinkedMap) map; assertEquals(-1, lm.indexOf(getOtherKeys())); resetFull(); lm = (LinkedMap) map; List list = new ArrayList(); for (MapIterator it = lm.mapIterator(); it.hasNext();) { list.add(it.next()); } for (int i = 0; i < list.size(); i++) { assertEquals(i, lm.indexOf(list.get(i))); } } public void testRemoveByIndex() { resetEmpty(); LinkedMap lm = (LinkedMap) map; try { lm.remove(0); } catch (IndexOutOfBoundsException ex) { } try { lm.remove(-1); } catch (IndexOutOfBoundsException ex) { } resetFull(); lm = (LinkedMap) map; try { lm.remove(-1); } catch (IndexOutOfBoundsException ex) { } try { lm.remove(lm.size()); } catch (IndexOutOfBoundsException ex) { } List list = new ArrayList(); for (MapIterator it = lm.mapIterator(); it.hasNext();) { list.add(it.next()); } for (int i = 0; i < list.size(); i++) { Object key = list.get(i); Object value = lm.get(key); assertEquals(value, lm.remove(i)); list.remove(i); assertEquals(false, lm.containsKey(key)); } } public BulkTest bulkTestListView() { return new TestListView(); } public class TestListView extends AbstractTestList { TestListView() { super("TestListView"); } public List makeEmptyList() { return ((LinkedMap) TestLinkedMap.this.makeEmptyMap()).asList(); } public List makeFullList() { return ((LinkedMap) TestLinkedMap.this.makeFullMap()).asList(); } public Object[] getFullElements() { return TestLinkedMap.this.getSampleKeys(); } public boolean isAddSupported() { return false; } public boolean isRemoveSupported() { return false; } public boolean isSetSupported() { return false; } public boolean isNullSupported() { return TestLinkedMap.this.isAllowNullKey(); } public boolean isTestSerialization() { return false; } } public void testClone() { LinkedMap map = new LinkedMap(10); map.put("1", "1"); Map cloned = (Map) map.clone(); assertEquals(map.size(), cloned.size()); assertSame(map.get("1"), cloned.get("1")); } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk((java.io.Serializable) map, "D:/dev/collections15/data/test/LinkedMap.emptyCollection.version3.obj"); // resetFull(); // writeExternalFormToDisk((java.io.Serializable) map, "D:/dev/collections15/data/test/LinkedMap.fullCollection.version3.obj"); // } } collections-generic-4.01/src/test/org/apache/commons/collections15/map/TestFlat3Map.java0000644000175000017500000002113210464140755031405 0ustar giovannigiovanni/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.map; import junit.framework.Test; import junit.textui.TestRunner; import org.apache.commons.collections15.BulkTest; import org.apache.commons.collections15.MapIterator; import org.apache.commons.collections15.iterators.AbstractTestMapIterator; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Map; /** * JUnit tests. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 19:11:58 $ */ public class TestFlat3Map extends AbstractTestIterableMap { private static final Integer ONE = new Integer(1); private static final Integer TWO = new Integer(2); private static final String TEN = "10"; private static final String TWENTY = "20"; public TestFlat3Map(String testName) { super(testName); } public static void main(String[] args) { TestRunner.run(suite()); } public static Test suite() { return BulkTest.makeSuite(TestFlat3Map.class); } public Map makeEmptyMap() { return new Flat3Map(); } //----------------------------------------------------------------------- public void testClone2() { Flat3Map map = new Flat3Map(); assertEquals(0, map.size()); map.put(ONE, TEN); map.put(TWO, TWENTY); assertEquals(2, map.size()); assertEquals(true, map.containsKey(ONE)); assertEquals(true, map.containsKey(TWO)); assertSame(TEN, map.get(ONE)); assertSame(TWENTY, map.get(TWO)); // clone works (size = 2) Flat3Map cloned = (Flat3Map) map.clone(); assertEquals(2, cloned.size()); assertEquals(true, cloned.containsKey(ONE)); assertEquals(true, cloned.containsKey(TWO)); assertSame(TEN, cloned.get(ONE)); assertSame(TWENTY, cloned.get(TWO)); // change original doesn't change clone map.put(TEN, ONE); map.put(TWENTY, TWO); assertEquals(4, map.size()); assertEquals(2, cloned.size()); assertEquals(true, cloned.containsKey(ONE)); assertEquals(true, cloned.containsKey(TWO)); assertSame(TEN, cloned.get(ONE)); assertSame(TWENTY, cloned.get(TWO)); } public void testClone4() { Flat3Map map = new Flat3Map(); assertEquals(0, map.size()); map.put(ONE, TEN); map.put(TWO, TWENTY); map.put(TEN, ONE); map.put(TWENTY, TWO); // clone works (size = 4) Flat3Map cloned = (Flat3Map) map.clone(); assertEquals(4, map.size()); assertEquals(4, cloned.size()); assertEquals(true, cloned.containsKey(ONE)); assertEquals(true, cloned.containsKey(TWO)); assertEquals(true, cloned.containsKey(TEN)); assertEquals(true, cloned.containsKey(TWENTY)); assertSame(TEN, cloned.get(ONE)); assertSame(TWENTY, cloned.get(TWO)); assertSame(ONE, cloned.get(TEN)); assertSame(TWO, cloned.get(TWENTY)); // change original doesn't change clone map.clear(); assertEquals(0, map.size()); assertEquals(4, cloned.size()); assertEquals(true, cloned.containsKey(ONE)); assertEquals(true, cloned.containsKey(TWO)); assertEquals(true, cloned.containsKey(TEN)); assertEquals(true, cloned.containsKey(TWENTY)); assertSame(TEN, cloned.get(ONE)); assertSame(TWENTY, cloned.get(TWO)); assertSame(ONE, cloned.get(TEN)); assertSame(TWO, cloned.get(TWENTY)); } public void testSerialisation0() throws Exception { Flat3Map map = new Flat3Map(); ByteArrayOutputStream bout = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(bout); out.writeObject(map); byte[] bytes = bout.toByteArray(); out.close(); ByteArrayInputStream bin = new ByteArrayInputStream(bytes); ObjectInputStream in = new ObjectInputStream(bin); Flat3Map ser = (Flat3Map) in.readObject(); in.close(); assertEquals(0, map.size()); assertEquals(0, ser.size()); } public void testSerialisation2() throws Exception { Flat3Map map = new Flat3Map(); map.put(ONE, TEN); map.put(TWO, TWENTY); ByteArrayOutputStream bout = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(bout); out.writeObject(map); byte[] bytes = bout.toByteArray(); out.close(); ByteArrayInputStream bin = new ByteArrayInputStream(bytes); ObjectInputStream in = new ObjectInputStream(bin); Flat3Map ser = (Flat3Map) in.readObject(); in.close(); assertEquals(2, map.size()); assertEquals(2, ser.size()); assertEquals(true, ser.containsKey(ONE)); assertEquals(true, ser.containsKey(TWO)); assertEquals(TEN, ser.get(ONE)); assertEquals(TWENTY, ser.get(TWO)); } public void testSerialisation4() throws Exception { Flat3Map map = new Flat3Map(); map.put(ONE, TEN); map.put(TWO, TWENTY); map.put(TEN, ONE); map.put(TWENTY, TWO); ByteArrayOutputStream bout = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(bout); out.writeObject(map); byte[] bytes = bout.toByteArray(); out.close(); ByteArrayInputStream bin = new ByteArrayInputStream(bytes); ObjectInputStream in = new ObjectInputStream(bin); Flat3Map ser = (Flat3Map) in.readObject(); in.close(); assertEquals(4, map.size()); assertEquals(4, ser.size()); assertEquals(true, ser.containsKey(ONE)); assertEquals(true, ser.containsKey(TWO)); assertEquals(true, ser.containsKey(TEN)); assertEquals(true, ser.containsKey(TWENTY)); assertEquals(TEN, ser.get(ONE)); assertEquals(TWENTY, ser.get(TWO)); assertEquals(ONE, ser.get(TEN)); assertEquals(TWO, ser.get(TWENTY)); } //----------------------------------------------------------------------- public BulkTest bulkTestMapIterator() { return new TestFlatMapIterator(); } public class TestFlatMapIterator extends AbstractTestMapIterator { public TestFlatMapIterator() { super("TestFlatMapIterator"); } public Object[] addSetValues() { return TestFlat3Map.this.getNewSampleValues(); } public boolean supportsRemove() { return TestFlat3Map.this.isRemoveSupported(); } public boolean supportsSetValue() { return TestFlat3Map.this.isSetValueSupported(); } public MapIterator makeEmptyMapIterator() { resetEmpty(); return ((Flat3Map) TestFlat3Map.this.map).mapIterator(); } public MapIterator makeFullMapIterator() { resetFull(); return ((Flat3Map) TestFlat3Map.this.map).mapIterator(); } public Map getMap() { // assumes makeFullMapIterator() called first return TestFlat3Map.this.map; } public Map getConfirmedMap() { // assumes makeFullMapIterator() called first return TestFlat3Map.this.confirmed; } public void verify() { super.verify(); TestFlat3Map.this.verify(); } } public String getCompatibilityVersion() { return "3.1"; } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk( // (java.io.Serializable) map, // "D:/dev/collections15/data/test/Flat3Map.emptyCollection.version3.1.obj"); // resetFull(); // writeExternalFormToDisk( // (java.io.Serializable) map, // "D:/dev/collections15/data/test/Flat3Map.fullCollection.version3.1.obj"); // } } collections-generic-4.01/src/test/org/apache/commons/collections15/map/TestListOrderedMap2.java0000644000175000017500000001436710464140764032752 0ustar giovannigiovanni/* * Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.map; import junit.framework.Test; import org.apache.commons.collections15.BulkTest; import org.apache.commons.collections15.MapIterator; import org.apache.commons.collections15.list.AbstractTestList; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * Extension of {@link TestMap} for exercising the {@link ListOrderedMap} * implementation. * * @author Henri Yandell * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 19:11:58 $ * @since Commons Collections 3.1 */ public class TestListOrderedMap2 extends AbstractTestOrderedMap { public TestListOrderedMap2(String testName) { super(testName); } public static Test suite() { return BulkTest.makeSuite(TestListOrderedMap2.class); } public static void main(String args[]) { String[] testCaseName = {TestListOrderedMap2.class.getName()}; junit.textui.TestRunner.main(testCaseName); } public Map makeEmptyMap() { return new ListOrderedMap(); } //----------------------------------------------------------------------- public void testGetByIndex() { resetEmpty(); ListOrderedMap lom = (ListOrderedMap) map; try { lom.get(0); } catch (IndexOutOfBoundsException ex) { } try { lom.get(-1); } catch (IndexOutOfBoundsException ex) { } resetFull(); lom = (ListOrderedMap) map; try { lom.get(-1); } catch (IndexOutOfBoundsException ex) { } try { lom.get(lom.size()); } catch (IndexOutOfBoundsException ex) { } int i = 0; for (MapIterator it = lom.mapIterator(); it.hasNext(); i++) { assertSame(it.next(), lom.get(i)); } } public void testGetValueByIndex() { resetEmpty(); ListOrderedMap lom = (ListOrderedMap) map; try { lom.getValue(0); } catch (IndexOutOfBoundsException ex) { } try { lom.getValue(-1); } catch (IndexOutOfBoundsException ex) { } resetFull(); lom = (ListOrderedMap) map; try { lom.getValue(-1); } catch (IndexOutOfBoundsException ex) { } try { lom.getValue(lom.size()); } catch (IndexOutOfBoundsException ex) { } int i = 0; for (MapIterator it = lom.mapIterator(); it.hasNext(); i++) { it.next(); assertSame(it.getValue(), lom.getValue(i)); } } public void testIndexOf() { resetEmpty(); ListOrderedMap lom = (ListOrderedMap) map; assertEquals(-1, lom.indexOf(getOtherKeys())); resetFull(); lom = (ListOrderedMap) map; List list = new ArrayList(); for (MapIterator it = lom.mapIterator(); it.hasNext();) { list.add(it.next()); } for (int i = 0; i < list.size(); i++) { assertEquals(i, lom.indexOf(list.get(i))); } } public void testRemoveByIndex() { resetEmpty(); ListOrderedMap lom = (ListOrderedMap) map; try { lom.remove(0); } catch (IndexOutOfBoundsException ex) { } try { lom.remove(-1); } catch (IndexOutOfBoundsException ex) { } resetFull(); lom = (ListOrderedMap) map; try { lom.remove(-1); } catch (IndexOutOfBoundsException ex) { } try { lom.remove(lom.size()); } catch (IndexOutOfBoundsException ex) { } List list = new ArrayList(); for (MapIterator it = lom.mapIterator(); it.hasNext();) { list.add(it.next()); } for (int i = 0; i < list.size(); i++) { Object key = list.get(i); Object value = lom.get(key); assertEquals(value, lom.remove(i)); list.remove(i); assertEquals(false, lom.containsKey(key)); } } public BulkTest bulkTestListView() { return new TestListView(); } public class TestListView extends AbstractTestList { TestListView() { super("TestListView"); } public List makeEmptyList() { return ((ListOrderedMap) TestListOrderedMap2.this.makeEmptyMap()).asList(); } public List makeFullList() { return ((ListOrderedMap) TestListOrderedMap2.this.makeFullMap()).asList(); } public Object[] getFullElements() { return TestListOrderedMap2.this.getSampleKeys(); } public boolean isAddSupported() { return false; } public boolean isRemoveSupported() { return false; } public boolean isSetSupported() { return false; } public boolean isNullSupported() { return TestListOrderedMap2.this.isAllowNullKey(); } public boolean isTestSerialization() { return false; } } public String getCompatibilityVersion() { return "3.1"; } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk( // (java.io.Serializable) map, // "D:/dev/collections15/data/test/ListOrderedMap.emptyCollection.version3.1.obj"); // resetFull(); // writeExternalFormToDisk( // (java.io.Serializable) map, // "D:/dev/collections15/data/test/ListOrderedMap.fullCollection.version3.1.obj"); // } } collections-generic-4.01/src/test/org/apache/commons/collections15/map/TestReferenceMap.java0000644000175000017500000002070110464140755032333 0ustar giovannigiovanni/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.map; import junit.framework.Test; import org.apache.commons.collections15.BulkTest; import java.lang.ref.WeakReference; import java.util.Map; /** * Tests for ReferenceMap. * * @author Matt Hall, John Watkinson, Paul Jack * @version $Revision: 1.1 $ $Date: 2005/10/11 19:11:58 $ */ public class TestReferenceMap extends AbstractTestIterableMap { public TestReferenceMap(String testName) { super(testName); } public static Test suite() { return BulkTest.makeSuite(TestReferenceMap.class); } public static void main(String args[]) { String[] testCaseName = {TestReferenceMap.class.getName()}; junit.textui.TestRunner.main(testCaseName); } public Map makeEmptyMap() { ReferenceMap map = new ReferenceMap(ReferenceMap.WEAK, ReferenceMap.WEAK); return map; } public boolean isAllowNullKey() { return false; } public boolean isAllowNullValue() { return false; } public String getCompatibilityVersion() { return "3.1"; } //----------------------------------------------------------------------- public void testNullHandling() { resetFull(); assertEquals(null, map.get(null)); assertEquals(false, map.containsKey(null)); assertEquals(false, map.containsValue(null)); assertEquals(null, map.remove(null)); assertEquals(false, map.entrySet().contains(null)); assertEquals(false, map.keySet().contains(null)); assertEquals(false, map.values().contains(null)); try { map.put(null, null); fail(); } catch (NullPointerException ex) { } try { map.put(new Object(), null); fail(); } catch (NullPointerException ex) { } try { map.put(null, new Object()); fail(); } catch (NullPointerException ex) { } } //----------------------------------------------------------------------- /* // Tests often fail because gc is uncontrollable public void testPurge() { ReferenceMap map = new ReferenceMap(ReferenceMap.WEAK, ReferenceMap.WEAK); Object[] hard = new Object[10]; for (int i = 0; i < hard.length; i++) { hard[i] = new Object(); map.put(hard[i], new Object()); } gc(); assertTrue("map should be empty after purge of weak values", map.isEmpty()); for (int i = 0; i < hard.length; i++) { map.put(new Object(), hard[i]); } gc(); assertTrue("map should be empty after purge of weak keys", map.isEmpty()); for (int i = 0; i < hard.length; i++) { map.put(new Object(), hard[i]); map.put(hard[i], new Object()); } gc(); assertTrue("map should be empty after purge of weak keys and values", map.isEmpty()); } public void testGetAfterGC() { ReferenceMap map = new ReferenceMap(ReferenceMap.WEAK, ReferenceMap.WEAK); for (int i = 0; i < 10; i++) { map.put(new Integer(i), new Integer(i)); } gc(); for (int i = 0; i < 10; i++) { Integer I = new Integer(i); assertTrue("map.containsKey should return false for GC'd element", !map.containsKey(I)); assertTrue("map.get should return null for GC'd element", map.get(I) == null); } } public void testEntrySetIteratorAfterGC() { ReferenceMap map = new ReferenceMap(ReferenceMap.WEAK, ReferenceMap.WEAK); Object[] hard = new Object[10]; for (int i = 0; i < 10; i++) { hard[i] = new Integer(10 + i); map.put(new Integer(i), new Integer(i)); map.put(hard[i], hard[i]); } gc(); Iterator iterator = map.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry entry = (Map.Entry)iterator.next(); Integer key = (Integer)entry.getKey(); Integer value = (Integer)entry.getValue(); assertTrue("iterator should skip GC'd keys", key.intValue() >= 10); assertTrue("iterator should skip GC'd values", value.intValue() >= 10); } } public void testMapIteratorAfterGC() { ReferenceMap map = new ReferenceMap(ReferenceMap.WEAK, ReferenceMap.WEAK); Object[] hard = new Object[10]; for (int i = 0; i < 10; i++) { hard[i] = new Integer(10 + i); map.put(new Integer(i), new Integer(i)); map.put(hard[i], hard[i]); } gc(); MapIterator iterator = map.mapIterator(); while (iterator.hasNext()) { Object key1 = iterator.next(); Integer key = (Integer) iterator.getKey(); Integer value = (Integer) iterator.getValue(); assertTrue("iterator keys should match", key == key1); assertTrue("iterator should skip GC'd keys", key.intValue() >= 10); assertTrue("iterator should skip GC'd values", value.intValue() >= 10); } } public void testMapIteratorAfterGC2() { ReferenceMap map = new ReferenceMap(ReferenceMap.WEAK, ReferenceMap.WEAK); Object[] hard = new Object[10]; for (int i = 0; i < 10; i++) { hard[i] = new Integer(10 + i); map.put(new Integer(i), new Integer(i)); map.put(hard[i], hard[i]); } MapIterator iterator = map.mapIterator(); while (iterator.hasNext()) { Object key1 = iterator.next(); gc(); Integer key = (Integer) iterator.getKey(); Integer value = (Integer) iterator.getValue(); assertTrue("iterator keys should match", key == key1); assertTrue("iterator should skip GC'd keys", key.intValue() >= 10); assertTrue("iterator should skip GC'd values", value.intValue() >= 10); } } */ /** * Tests whether purge values setting works */ public void testPurgeValues() throws Exception { // many thanks to Juozas Baliuka for suggesting this method Object key = new Object(); Object value = new Object(); WeakReference keyReference = new WeakReference(key); WeakReference valueReference = new WeakReference(value); Map testMap = new ReferenceMap(ReferenceMap.WEAK, ReferenceMap.HARD, true); testMap.put(key, value); assertEquals("In map", value, testMap.get(key)); assertNotNull("Weak reference released early (1)", keyReference.get()); assertNotNull("Weak reference released early (2)", valueReference.get()); // dereference strong references key = null; value = null; int iterations = 0; int bytz = 2; while (true) { System.gc(); if (iterations++ > 50) { fail("Max iterations reached before resource released."); } testMap.isEmpty(); if (keyReference.get() == null && valueReference.get() == null) { break; } else { // create garbage: byte[] b = new byte[bytz]; bytz = bytz * 2; } } } private static void gc() { try { // trigger GC byte[][] tooLarge = new byte[1000000000][1000000000]; fail("you have too much RAM"); } catch (OutOfMemoryError ex) { System.gc(); // ignore } } } collections-generic-4.01/src/test/org/apache/commons/collections15/map/TestPredicatedMap.java0000644000175000017500000001124210464140761032476 0ustar giovannigiovanni/* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.map; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.collections15.Predicate; import org.apache.commons.collections15.PredicateUtils; import java.util.HashMap; import java.util.Iterator; import java.util.Map; /** * Extension of {@link TestMap} for exercising the * {@link PredicatedMap} implementation. * * @author Matt Hall, John Watkinson, Phil Steitz * @version $Revision: 1.1 $ $Date: 2005/10/11 19:11:58 $ * @since Commons Collections 3.0 */ public class TestPredicatedMap extends AbstractTestMap { protected static final Predicate truePredicate = PredicateUtils.truePredicate(); protected static final Predicate testPredicate = new Predicate() { public boolean evaluate(Object o) { return (o instanceof String); } }; public TestPredicatedMap(String testName) { super(testName); } public static Test suite() { return new TestSuite(TestPredicatedMap.class); } public static void main(String args[]) { String[] testCaseName = {TestPredicatedMap.class.getName()}; junit.textui.TestRunner.main(testCaseName); } //----------------------------------------------------------------------- protected Map decorateMap(Map map, Predicate keyPredicate, Predicate valuePredicate) { return PredicatedMap.decorate(map, keyPredicate, valuePredicate); } public Map makeEmptyMap() { return decorateMap(new HashMap(), truePredicate, truePredicate); } public Map makeTestMap() { return decorateMap(new HashMap(), testPredicate, testPredicate); } //----------------------------------------------------------------------- public void testEntrySet() { Map map = makeTestMap(); assertTrue("returned entryset should not be null", map.entrySet() != null); map = decorateMap(new HashMap(), null, null); map.put("oneKey", "oneValue"); assertTrue("returned entryset should contain one entry", map.entrySet().size() == 1); map = decorateMap(map, null, null); } public void testPut() { Map map = makeTestMap(); try { map.put("Hi", new Integer(3)); fail("Illegal value should raise IllegalArgument"); } catch (IllegalArgumentException e) { // expected } try { map.put(new Integer(3), "Hi"); fail("Illegal key should raise IllegalArgument"); } catch (IllegalArgumentException e) { // expected } assertTrue(!map.containsKey(new Integer(3))); assertTrue(!map.containsValue(new Integer(3))); Map map2 = new HashMap(); map2.put("A", "a"); map2.put("B", "b"); map2.put("C", "c"); map2.put("c", new Integer(3)); try { map.putAll(map2); fail("Illegal value should raise IllegalArgument"); } catch (IllegalArgumentException e) { // expected } map.put("E", "e"); Iterator iterator = map.entrySet().iterator(); try { Map.Entry entry = (Map.Entry) iterator.next(); entry.setValue(new Integer(3)); fail("Illegal value should raise IllegalArgument"); } catch (IllegalArgumentException e) { // expected } map.put("F", "f"); iterator = map.entrySet().iterator(); Map.Entry entry = (Map.Entry) iterator.next(); entry.setValue("x"); } public String getCompatibilityVersion() { return "3.1"; } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk( // (java.io.Serializable) map, // "D:/dev/collections15/data/test/PredicatedMap.emptyCollection.version3.1.obj"); // resetFull(); // writeExternalFormToDisk( // (java.io.Serializable) map, // "D:/dev/collections15/data/test/PredicatedMap.fullCollection.version3.1.obj"); // } }collections-generic-4.01/src/test/org/apache/commons/collections15/map/TestTransformedSortedMap.java0000644000175000017500000001134510464140755034106 0ustar giovannigiovanni/* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.map; import junit.framework.Test; import org.apache.commons.collections15.BulkTest; import org.apache.commons.collections15.TransformerUtils; import org.apache.commons.collections15.collection.TestTransformedCollection; import java.util.Map; import java.util.Set; import java.util.TreeMap; /** * Extension of {@link AbstractTestSortedMap} for exercising the {@link TransformedSortedMap} * implementation. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:06:04 $ * @since Commons Collections 3.0 */ public class TestTransformedSortedMap extends AbstractTestSortedMap { public TestTransformedSortedMap(String testName) { super(testName); } public static Test suite() { return BulkTest.makeSuite(TestTransformedSortedMap.class); } public static void main(String args[]) { String[] testCaseName = {TestTransformedSortedMap.class.getName()}; junit.textui.TestRunner.main(testCaseName); } //----------------------------------------------------------------------- public Map makeEmptyMap() { return TransformedSortedMap.decorate(new TreeMap(), TransformerUtils.nopTransformer(), TransformerUtils.nopTransformer()); } public boolean isSubMapViewsSerializable() { // TreeMap sub map views have a bug in deserialization. return false; } //----------------------------------------------------------------------- public void testTransformedMap() { Object[] els = new Object[]{"1", "3", "5", "7", "2", "4", "6"}; Map map = TransformedSortedMap.decorate(new TreeMap(), TestTransformedCollection.STRING_TO_INTEGER_TRANSFORMER, null); assertEquals(0, map.size()); for (int i = 0; i < els.length; i++) { map.put(els[i], els[i]); assertEquals(i + 1, map.size()); assertEquals(true, map.containsKey(new Integer((String) els[i]))); try { map.containsKey(els[i]); fail(); } catch (ClassCastException ex) { } assertEquals(true, map.containsValue(els[i])); assertEquals(els[i], map.get(new Integer((String) els[i]))); } try { map.remove(els[0]); fail(); } catch (ClassCastException ex) { } assertEquals(els[0], map.remove(new Integer((String) els[0]))); map = TransformedSortedMap.decorate(new TreeMap(), null, TestTransformedCollection.STRING_TO_INTEGER_TRANSFORMER); assertEquals(0, map.size()); for (int i = 0; i < els.length; i++) { map.put(els[i], els[i]); assertEquals(i + 1, map.size()); assertEquals(true, map.containsValue(new Integer((String) els[i]))); assertEquals(false, map.containsValue(els[i])); assertEquals(true, map.containsKey(els[i])); assertEquals(new Integer((String) els[i]), map.get(els[i])); } assertEquals(new Integer((String) els[0]), map.remove(els[0])); Set entrySet = map.entrySet(); Map.Entry[] array = (Map.Entry[]) entrySet.toArray(new Map.Entry[0]); array[0].setValue("66"); assertEquals(new Integer(66), array[0].getValue()); assertEquals(new Integer(66), map.get(array[0].getKey())); Map.Entry entry = (Map.Entry) entrySet.iterator().next(); entry.setValue("88"); assertEquals(new Integer(88), entry.getValue()); assertEquals(new Integer(88), map.get(entry.getKey())); } public String getCompatibilityVersion() { return "3.1"; } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk( // (java.io.Serializable) map, // "D:/dev/collections15/data/test/TransformedSortedMap.emptyCollection.version3.1.obj"); // resetFull(); // writeExternalFormToDisk( // (java.io.Serializable) map, // "D:/dev/collections15/data/test/TransformedSortedMap.fullCollection.version3.1.obj"); // } } collections-generic-4.01/src/test/org/apache/commons/collections15/map/TestIdentityMap.java0000644000175000017500000001206610464140762032231 0ustar giovannigiovanni/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.map; import junit.framework.Test; import junit.framework.TestSuite; import junit.textui.TestRunner; import org.apache.commons.collections15.AbstractTestObject; import org.apache.commons.collections15.IterableMap; import java.io.IOException; import java.io.Serializable; import java.util.Iterator; import java.util.Map; /** * JUnit tests. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 19:11:58 $ */ public class TestIdentityMap extends AbstractTestObject { private static final Integer I1A = new Integer(1); private static final Integer I1B = new Integer(1); private static final Integer I2A = new Integer(2); private static final Integer I2B = new Integer(2); public TestIdentityMap(String testName) { super(testName); } public static void main(String[] args) { TestRunner.run(suite()); } public static Test suite() { return new TestSuite(TestIdentityMap.class); // return BulkTest.makeSuite(TestIdentityMap.class); // causes race condition! } public Object makeObject() { return new IdentityMap(); } public String getCompatibilityVersion() { return "3"; } //----------------------------------------------------------------------- public void testBasics() { IterableMap map = new IdentityMap(); assertEquals(0, map.size()); map.put(I1A, I2A); assertEquals(1, map.size()); assertSame(I2A, map.get(I1A)); assertSame(null, map.get(I1B)); assertEquals(true, map.containsKey(I1A)); assertEquals(false, map.containsKey(I1B)); assertEquals(true, map.containsValue(I2A)); assertEquals(false, map.containsValue(I2B)); map.put(I1A, I2B); assertEquals(1, map.size()); assertSame(I2B, map.get(I1A)); assertSame(null, map.get(I1B)); assertEquals(true, map.containsKey(I1A)); assertEquals(false, map.containsKey(I1B)); assertEquals(false, map.containsValue(I2A)); assertEquals(true, map.containsValue(I2B)); map.put(I1B, I2B); assertEquals(2, map.size()); assertSame(I2B, map.get(I1A)); assertSame(I2B, map.get(I1B)); assertEquals(true, map.containsKey(I1A)); assertEquals(true, map.containsKey(I1B)); assertEquals(false, map.containsValue(I2A)); assertEquals(true, map.containsValue(I2B)); } //----------------------------------------------------------------------- public void testHashEntry() { IterableMap map = new IdentityMap(); map.put(I1A, I2A); map.put(I1B, I2A); Map.Entry entry1 = (Map.Entry) map.entrySet().iterator().next(); Iterator it = map.entrySet().iterator(); Map.Entry entry2 = (Map.Entry) it.next(); Map.Entry entry3 = (Map.Entry) it.next(); assertEquals(true, entry1.equals(entry2)); assertEquals(true, entry2.equals(entry1)); assertEquals(false, entry1.equals(entry3)); } /** * Compare the current serialized form of the Map * against the canonical version in CVS. */ public void testEmptyMapCompatibility() throws IOException, ClassNotFoundException { // test to make sure the canonical form has been preserved // Disabled as binary compatibility with 3.0 is not supported. // Map map = (Map) makeObject(); // if (map instanceof Serializable && !skipSerializedCanonicalTests()) { // Map map2 = (Map) readExternalFormFromDisk(getCanonicalEmptyCollectionName(map)); // assertEquals("Map is empty", 0, map2.size()); // } } public void testClone() { IdentityMap map = new IdentityMap(10); map.put("1", "1"); Map cloned = (Map) map.clone(); assertEquals(map.size(), cloned.size()); assertSame(map.get("1"), cloned.get("1")); } // public void testCreate() throws Exception { // Map map = new IdentityMap(); // writeExternalFormToDisk((java.io.Serializable) map, "D:/dev/collections15/data/test/IdentityMap.emptyCollection.version3.obj"); // map = new IdentityMap(); // map.put(I1A, I2A); // map.put(I1B, I2A); // map.put(I2A, I2B); // writeExternalFormToDisk((java.io.Serializable) map, "D:/dev/collections15/data/test/IdentityMap.fullCollection.version3.obj"); // } } collections-generic-4.01/src/test/org/apache/commons/collections15/map/AbstractTestOrderedMap.java0000644000175000017500000001622610464140760033510 0ustar giovannigiovanni/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.map; import org.apache.commons.collections15.BulkTest; import org.apache.commons.collections15.MapIterator; import org.apache.commons.collections15.OrderedMap; import org.apache.commons.collections15.comparators.ComparableComparator; import org.apache.commons.collections15.comparators.NullComparator; import org.apache.commons.collections15.iterators.AbstractTestOrderedMapIterator; import java.util.*; /** * Abstract test class for {@link OrderedMap} methods and contracts. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 19:11:58 $ */ public abstract class AbstractTestOrderedMap extends AbstractTestIterableMap { /** * JUnit constructor. * * @param testName the test name */ public AbstractTestOrderedMap(String testName) { super(testName); } //----------------------------------------------------------------------- /** * OrderedMap uses TreeMap as its known comparison. * * @return a map that is known to be valid */ public Map makeConfirmedMap() { return new TreeMap(new NullComparator(ComparableComparator.getInstance())); } /** * The only confirmed collection we have that is ordered is the sorted one. * Thus, sort the keys. */ public Object[] getSampleKeys() { List list = new ArrayList(Arrays.asList(super.getSampleKeys())); Collections.sort(list, new NullComparator(ComparableComparator.getInstance())); return list.toArray(); } //----------------------------------------------------------------------- public void testFirstKey() { resetEmpty(); OrderedMap ordered = (OrderedMap) map; try { ordered.firstKey(); fail(); } catch (NoSuchElementException ex) { } resetFull(); ordered = (OrderedMap) map; Object confirmedFirst = confirmed.keySet().iterator().next(); assertEquals(confirmedFirst, ordered.firstKey()); } public void testLastKey() { resetEmpty(); OrderedMap ordered = (OrderedMap) map; try { ordered.lastKey(); fail(); } catch (NoSuchElementException ex) { } resetFull(); ordered = (OrderedMap) map; Object confirmedLast = null; for (Iterator it = confirmed.keySet().iterator(); it.hasNext();) { confirmedLast = it.next(); } assertEquals(confirmedLast, ordered.lastKey()); } //----------------------------------------------------------------------- public void testNextKey() { resetEmpty(); OrderedMap ordered = (OrderedMap) map; assertEquals(null, ordered.nextKey(getOtherKeys()[0])); if (isAllowNullKey() == false) { try { assertEquals(null, ordered.nextKey(null)); // this is allowed too } catch (NullPointerException ex) { } } else { assertEquals(null, ordered.nextKey(null)); } resetFull(); ordered = (OrderedMap) map; Iterator it = confirmed.keySet().iterator(); Object confirmedLast = it.next(); while (it.hasNext()) { Object confirmedObject = it.next(); assertEquals(confirmedObject, ordered.nextKey(confirmedLast)); confirmedLast = confirmedObject; } assertEquals(null, ordered.nextKey(confirmedLast)); if (isAllowNullKey() == false) { try { ordered.nextKey(null); fail(); } catch (NullPointerException ex) { } } else { assertEquals(null, ordered.nextKey(null)); } } public void testPreviousKey() { resetEmpty(); OrderedMap ordered = (OrderedMap) map; assertEquals(null, ordered.previousKey(getOtherKeys()[0])); if (isAllowNullKey() == false) { try { assertEquals(null, ordered.previousKey(null)); // this is allowed too } catch (NullPointerException ex) { } } else { assertEquals(null, ordered.previousKey(null)); } resetFull(); ordered = (OrderedMap) map; List list = new ArrayList(confirmed.keySet()); Collections.reverse(list); Iterator it = list.iterator(); Object confirmedLast = it.next(); while (it.hasNext()) { Object confirmedObject = it.next(); assertEquals(confirmedObject, ordered.previousKey(confirmedLast)); confirmedLast = confirmedObject; } assertEquals(null, ordered.previousKey(confirmedLast)); if (isAllowNullKey() == false) { try { ordered.previousKey(null); fail(); } catch (NullPointerException ex) { } } else { if (isAllowNullKey() == false) { assertEquals(null, ordered.previousKey(null)); } } } //----------------------------------------------------------------------- public BulkTest bulkTestOrderedMapIterator() { return new InnerTestOrderedMapIterator(); } public class InnerTestOrderedMapIterator extends AbstractTestOrderedMapIterator { public InnerTestOrderedMapIterator() { super("InnerTestOrderedMapIterator"); } public boolean supportsRemove() { return AbstractTestOrderedMap.this.isRemoveSupported(); } public boolean isGetStructuralModify() { return AbstractTestOrderedMap.this.isGetStructuralModify(); } public boolean supportsSetValue() { return AbstractTestOrderedMap.this.isSetValueSupported(); } public MapIterator makeEmptyMapIterator() { resetEmpty(); return ((OrderedMap) AbstractTestOrderedMap.this.map).orderedMapIterator(); } public MapIterator makeFullMapIterator() { resetFull(); return ((OrderedMap) AbstractTestOrderedMap.this.map).orderedMapIterator(); } public Map getMap() { // assumes makeFullMapIterator() called first return AbstractTestOrderedMap.this.map; } public Map getConfirmedMap() { // assumes makeFullMapIterator() called first return AbstractTestOrderedMap.this.confirmed; } public void verify() { super.verify(); AbstractTestOrderedMap.this.verify(); } } } collections-generic-4.01/src/test/org/apache/commons/collections15/map/TestSingletonMap.java0000644000175000017500000001347210464140762032404 0ustar giovannigiovanni/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.map; import junit.framework.Test; import junit.textui.TestRunner; import org.apache.commons.collections15.BoundedMap; import org.apache.commons.collections15.BulkTest; import org.apache.commons.collections15.KeyValue; import java.util.HashMap; import java.util.Map; /** * JUnit tests. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 19:11:58 $ */ public class TestSingletonMap extends AbstractTestOrderedMap { private static final Integer ONE = new Integer(1); private static final Integer TWO = new Integer(2); private static final String TEN = "10"; private static final String TWENTY = "20"; public TestSingletonMap(String testName) { super(testName); } public static void main(String[] args) { TestRunner.run(suite()); } public static Test suite() { return BulkTest.makeSuite(TestSingletonMap.class); } //----------------------------------------------------------------------- public Map makeEmptyMap() { // need an empty singleton map, but thats not possible // use a ridiculous fake instead to make the tests pass return UnmodifiableOrderedMap.decorate(ListOrderedMap.decorate(new HashMap())); } public String[] ignoredTests() { // the ridiculous map above still doesn't pass these tests // but its not relevant, so we ignore them return new String[]{"TestSingletonMap.bulkTestMapIterator.testEmptyMapIterator", "TestSingletonMap.bulkTestOrderedMapIterator.testEmptyMapIterator", }; } public Map makeFullMap() { return new SingletonMap(ONE, TWO); } public boolean isPutAddSupported() { return false; } public boolean isRemoveSupported() { return false; } public Object[] getSampleKeys() { return new Object[]{ONE}; } public Object[] getSampleValues() { return new Object[]{TWO}; } public Object[] getNewSampleValues() { return new Object[]{TEN}; } //----------------------------------------------------------------------- public void testClone() { SingletonMap map = new SingletonMap(ONE, TWO); assertEquals(1, map.size()); SingletonMap cloned = (SingletonMap) map.clone(); assertEquals(1, cloned.size()); assertEquals(true, cloned.containsKey(ONE)); assertEquals(true, cloned.containsValue(TWO)); } public void testKeyValue() { SingletonMap map = new SingletonMap(ONE, TWO); assertEquals(1, map.size()); assertEquals(ONE, map.getKey()); assertEquals(TWO, map.getValue()); assertTrue(map instanceof KeyValue); } public void testBoundedMap() { SingletonMap map = new SingletonMap(ONE, TWO); assertEquals(1, map.size()); assertEquals(true, map.isFull()); assertEquals(1, map.maxSize()); assertTrue(map instanceof BoundedMap); } //----------------------------------------------------------------------- // public BulkTest bulkTestMapIterator() { // return new TestFlatMapIterator(); // } // // public class TestFlatMapIterator extends AbstractTestOrderedMapIterator { // public TestFlatMapIterator() { // super("TestFlatMapIterator"); // } // // public Object[] addSetValues() { // return TestSingletonMap.this.getNewSampleValues(); // } // // public boolean supportsRemove() { // return TestSingletonMap.this.isRemoveSupported(); // } // // public boolean supportsSetValue() { // return TestSingletonMap.this.isSetValueSupported(); // } // // public MapIterator makeEmptyMapIterator() { // resetEmpty(); // return ((Flat3Map) TestSingletonMap.this.map).mapIterator(); // } // // public MapIterator makeFullMapIterator() { // resetFull(); // return ((Flat3Map) TestSingletonMap.this.map).mapIterator(); // } // // public Map getMap() { // // assumes makeFullMapIterator() called first // return TestSingletonMap.this.map; // } // // public Map getConfirmedMap() { // // assumes makeFullMapIterator() called first // return TestSingletonMap.this.confirmed; // } // // public void verify() { // super.verify(); // TestSingletonMap.this.verify(); // } // } public String getCompatibilityVersion() { return "3.1"; } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk( // (java.io.Serializable) map, // "D:/dev/collections15/data/test/SingletonMap.emptyCollection.version3.1.obj"); // resetFull(); // writeExternalFormToDisk( // (java.io.Serializable) map, // "D:/dev/collections15/data/test/SingletonMap.fullCollection.version3.1.obj"); // } } collections-generic-4.01/src/test/org/apache/commons/collections15/map/TestFixedSizeMap.java0000644000175000017500000000452510464140762032333 0ustar giovannigiovanni/* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.map; import junit.framework.Test; import junit.framework.TestSuite; import java.util.HashMap; import java.util.Map; /** * Extension of {@link AbstractTestMap} for exercising the {@link FixedSizeMap} * implementation. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 19:11:58 $ * @since Commons Collections 3.0 */ public class TestFixedSizeMap extends AbstractTestMap { public TestFixedSizeMap(String testName) { super(testName); } public static Test suite() { return new TestSuite(TestFixedSizeMap.class); } public static void main(String args[]) { String[] testCaseName = {TestFixedSizeMap.class.getName()}; junit.textui.TestRunner.main(testCaseName); } public Map makeEmptyMap() { return FixedSizeMap.decorate(new HashMap()); } public Map makeFullMap() { Map map = new HashMap(); addSampleMappings(map); return FixedSizeMap.decorate(map); } public boolean isPutAddSupported() { return false; } public boolean isRemoveSupported() { return false; } public String getCompatibilityVersion() { return "3.1"; } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk( // (java.io.Serializable) map, // "D:/dev/collections15/data/test/FixedSizeMap.emptyCollection.version3.1.obj"); // resetFull(); // writeExternalFormToDisk( // (java.io.Serializable) map, // "D:/dev/collections15/data/test/FixedSizeMap.fullCollection.version3.1.obj"); // } } collections-generic-4.01/src/test/org/apache/commons/collections15/map/TestCompositeMap.java0000644000175000017500000001471210464140762032402 0ustar giovannigiovanni/* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.map; import junit.framework.Assert; import junit.framework.Test; import junit.framework.TestSuite; import java.util.Collection; import java.util.HashMap; import java.util.Map; /** * Extension of {@link AbstractTestMap} for exercising the * {@link CompositeMap} implementation. * * @author Matt Hall, John Watkinson, Brian McCallister * @version $Revision: 1.1 $ $Date: 2005/10/11 19:11:58 $ * @since Commons Collections 3.0 */ public class TestCompositeMap extends AbstractTestMap { /** * used as a flag in MapMutator tests */ private boolean pass = false; public TestCompositeMap(String testName) { super(testName); } public static Test suite() { return new TestSuite(TestCompositeMap.class); } public void setUp() throws Exception { super.setUp(); this.pass = false; } public static void main(String args[]) { String[] testCaseName = {TestCompositeMap.class.getName()}; junit.textui.TestRunner.main(testCaseName); } public Map makeEmptyMap() { CompositeMap map = new CompositeMap(); map.addComposited(new HashMap()); map.setMutator(new CompositeMap.MapMutator() { public void resolveCollision(CompositeMap composite, Map existing, Map added, Collection intersect) { // Do nothing } public Object put(CompositeMap map, Map[] composited, Object key, Object value) { return composited[0].put(key, value); } public void putAll(CompositeMap map, Map[] composited, Map t) { composited[0].putAll(t); } }); return map; } private Map buildOne() { HashMap map = new HashMap(); map.put("1", "one"); map.put("2", "two"); return map; } public Map buildTwo() { HashMap map = new HashMap(); map.put("3", "three"); map.put("4", "four"); return map; } public void testGet() { CompositeMap map = new CompositeMap(buildOne(), buildTwo()); Assert.assertEquals("one", map.get("1")); Assert.assertEquals("four", map.get("4")); } public void testAddComposited() { CompositeMap map = new CompositeMap(buildOne(), buildTwo()); HashMap three = new HashMap(); three.put("5", "five"); map.addComposited(three); assertTrue(map.containsKey("5")); try { map.addComposited(three); fail("Expecting IllegalArgumentException."); } catch (IllegalArgumentException ex) { // expected } } public void testRemoveComposited() { CompositeMap map = new CompositeMap(buildOne(), buildTwo()); HashMap three = new HashMap(); three.put("5", "five"); map.addComposited(three); assertTrue(map.containsKey("5")); map.removeComposited(three); assertFalse(map.containsKey("5")); map.removeComposited(buildOne()); assertFalse(map.containsKey("2")); } public void testRemoveFromUnderlying() { CompositeMap map = new CompositeMap(buildOne(), buildTwo()); HashMap three = new HashMap(); three.put("5", "five"); map.addComposited(three); assertTrue(map.containsKey("5")); //Now remove "5" three.remove("5"); assertFalse(map.containsKey("5")); } public void testRemoveFromComposited() { CompositeMap map = new CompositeMap(buildOne(), buildTwo()); HashMap three = new HashMap(); three.put("5", "five"); map.addComposited(three); assertTrue(map.containsKey("5")); //Now remove "5" map.remove("5"); assertFalse(three.containsKey("5")); } public void testResolveCollision() { CompositeMap map = new CompositeMap(buildOne(), buildTwo(), new CompositeMap.MapMutator() { public void resolveCollision(CompositeMap composite, Map existing, Map added, Collection intersect) { pass = true; } public Object put(CompositeMap map, Map[] composited, Object key, Object value) { throw new UnsupportedOperationException(); } public void putAll(CompositeMap map, Map[] composited, Map t) { throw new UnsupportedOperationException(); } }); map.addComposited(buildOne()); assertTrue(pass); } public void testPut() { CompositeMap map = new CompositeMap(buildOne(), buildTwo(), new CompositeMap.MapMutator() { public void resolveCollision(CompositeMap composite, Map existing, Map added, Collection intersect) { throw new UnsupportedOperationException(); } public Object put(CompositeMap map, Map[] composited, Object key, Object value) { pass = true; return "foo"; } public void putAll(CompositeMap map, Map[] composited, Map t) { throw new UnsupportedOperationException(); } }); map.put("willy", "wonka"); assertTrue(pass); } public void testPutAll() { CompositeMap map = new CompositeMap(buildOne(), buildTwo(), new CompositeMap.MapMutator() { public void resolveCollision(CompositeMap composite, Map existing, Map added, Collection intersect) { throw new UnsupportedOperationException(); } public Object put(CompositeMap map, Map[] composited, Object key, Object value) { throw new UnsupportedOperationException(); } public void putAll(CompositeMap map, Map[] composited, Map t) { pass = true; } }); map.putAll(null); assertTrue(pass); } } collections-generic-4.01/src/test/org/apache/commons/collections15/map/TestUnmodifiableMap.java0000644000175000017500000000607610464140762033042 0ustar giovannigiovanni/* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.map; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.collections15.Unmodifiable; import java.util.HashMap; import java.util.Map; /** * Extension of {@link AbstractTestMap} for exercising the * {@link UnmodifiableMap} implementation. * * @author Matt Hall, John Watkinson, Phil Steitz * @version $Revision: 1.1 $ $Date: 2005/10/11 17:06:04 $ * @since Commons Collections 3.0 */ public class TestUnmodifiableMap extends AbstractTestIterableMap { public TestUnmodifiableMap(String testName) { super(testName); } public static Test suite() { return new TestSuite(TestUnmodifiableMap.class); } public static void main(String args[]) { String[] testCaseName = {TestUnmodifiableMap.class.getName()}; junit.textui.TestRunner.main(testCaseName); } //------------------------------------------------------------------- public Map makeEmptyMap() { return UnmodifiableMap.decorate(new HashMap()); } public boolean isPutChangeSupported() { return false; } public boolean isPutAddSupported() { return false; } public boolean isRemoveSupported() { return false; } public Map makeFullMap() { Map m = new HashMap(); addSampleMappings(m); return UnmodifiableMap.decorate(m); } //----------------------------------------------------------------------- public void testUnmodifiable() { assertTrue(makeEmptyMap() instanceof Unmodifiable); assertTrue(makeFullMap() instanceof Unmodifiable); } public void testDecorateFactory() { Map map = makeFullMap(); assertSame(map, UnmodifiableMap.decorate(map)); try { UnmodifiableMap.decorate(null); fail(); } catch (IllegalArgumentException ex) { } } public String getCompatibilityVersion() { return "3.1"; } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk( // (java.io.Serializable) map, // "D:/dev/collections15/data/test/UnmodifiableMap.emptyCollection.version3.1.obj"); // resetFull(); // writeExternalFormToDisk( // (java.io.Serializable) map, // "D:/dev/collections15/data/test/UnmodifiableMap.fullCollection.version3.1.obj"); // } }collections-generic-4.01/src/test/org/apache/commons/collections15/map/TestAll.java0000644000175000017500000000506610464140763030515 0ustar giovannigiovanni/* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.map; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * Entry point for tests. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 19:11:58 $ * @since Commons Collections 3.0 */ public class TestAll extends TestCase { public TestAll(String testName) { super(testName); } public static void main(String args[]) { String[] testCaseName = {TestAll.class.getName()}; junit.textui.TestRunner.main(testCaseName); } public static Test suite() { TestSuite suite = new TestSuite(); suite.addTest(TestCaseInsensitiveMap.suite()); suite.addTest(TestCompositeMap.suite()); suite.addTest(TestFlat3Map.suite()); suite.addTest(TestHashedMap.suite()); suite.addTest(TestIdentityMap.suite()); suite.addTest(TestLinkedMap.suite()); suite.addTest(TestLRUMap.suite()); suite.addTest(TestMultiKeyMap.suite()); suite.addTest(TestReferenceMap.suite()); suite.addTest(TestReferenceIdentityMap.suite()); suite.addTest(TestStaticBucketMap.suite()); suite.addTest(TestSingletonMap.suite()); suite.addTest(TestFixedSizeMap.suite()); suite.addTest(TestFixedSizeSortedMap.suite()); suite.addTest(TestLazyMap.suite()); suite.addTest(TestLazySortedMap.suite()); suite.addTest(TestListOrderedMap.suite()); suite.addTest(TestListOrderedMap2.suite()); suite.addTest(TestPredicatedMap.suite()); suite.addTest(TestPredicatedSortedMap.suite()); suite.addTest(TestTransformedMap.suite()); suite.addTest(TestTransformedSortedMap.suite()); suite.addTest(TestUnmodifiableMap.suite()); suite.addTest(TestUnmodifiableOrderedMap.suite()); suite.addTest(TestUnmodifiableSortedMap.suite()); return suite; } } collections-generic-4.01/src/test/org/apache/commons/collections15/map/TestFixedSizeSortedMap.java0000644000175000017500000000536010464140764033514 0ustar giovannigiovanni/* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.map; import junit.framework.Test; import org.apache.commons.collections15.BulkTest; import java.util.Map; import java.util.SortedMap; import java.util.TreeMap; /** * Extension of {@link TestSortedMap} for exercising the {@link FixedSizeSortedMap} * implementation. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 19:11:58 $ * @since Commons Collections 3.0 */ public class TestFixedSizeSortedMap extends AbstractTestSortedMap { public TestFixedSizeSortedMap(String testName) { super(testName); } public static Test suite() { return BulkTest.makeSuite(TestFixedSizeSortedMap.class); } public static void main(String args[]) { String[] testCaseName = {TestFixedSizeSortedMap.class.getName()}; junit.textui.TestRunner.main(testCaseName); } //----------------------------------------------------------------------- public Map makeEmptyMap() { return FixedSizeSortedMap.decorate(new TreeMap()); } public Map makeFullMap() { SortedMap map = new TreeMap(); addSampleMappings(map); return FixedSizeSortedMap.decorate(map); } public boolean isSubMapViewsSerializable() { // TreeMap sub map views have a bug in deserialization. return false; } public boolean isPutAddSupported() { return false; } public boolean isRemoveSupported() { return false; } //----------------------------------------------------------------------- public String getCompatibilityVersion() { return "3.1"; } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk( // (java.io.Serializable) map, // "D:/dev/collections15/data/test/FixedSizeSortedMap.emptyCollection.version3.1.obj"); // resetFull(); // writeExternalFormToDisk( // (java.io.Serializable) map, // "D:/dev/collections15/data/test/FixedSizeSortedMap.fullCollection.version3.1.obj"); // } } collections-generic-4.01/src/test/org/apache/commons/collections15/map/TestCaseInsensitiveMap.java0000644000175000017500000001015510464140756033534 0ustar giovannigiovanni/* * Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.map; import junit.framework.Test; import junit.textui.TestRunner; import org.apache.commons.collections15.BulkTest; import java.util.HashMap; import java.util.Map; import java.util.Set; /** * Tests for the {@link CaseInsensitiveMap} implementation. * * @author Matt Hall, John Watkinson, Commons-Collections team * @version $Revision: 1.1 $ $Date: 2005/10/11 19:11:58 $ */ public class TestCaseInsensitiveMap extends AbstractTestIterableMap { public TestCaseInsensitiveMap(String testName) { super(testName); } public static void main(String[] args) { TestRunner.run(suite()); } public static Test suite() { return BulkTest.makeSuite(TestCaseInsensitiveMap.class); } public Map makeEmptyMap() { return new CaseInsensitiveMap(); } public String getCompatibilityVersion() { return "3"; } //------------------------------------------------------------------------- public void testCaseInsensitive() { Map map = new CaseInsensitiveMap(); map.put("One", "One"); map.put("Two", "Two"); assertEquals("One", (String) map.get("one")); assertEquals("One", (String) map.get("oNe")); map.put("two", "Three"); assertEquals("Three", (String) map.get("Two")); } public void testNullHandling() { Map map = new CaseInsensitiveMap(); map.put("One", "One"); map.put("Two", "Two"); map.put(null, "Three"); assertEquals("Three", (String) map.get(null)); map.put(null, "Four"); assertEquals("Four", (String) map.get(null)); Set keys = map.keySet(); assertTrue(keys.contains("one")); assertTrue(keys.contains("two")); assertTrue(keys.contains(null)); assertTrue(keys.size() == 3); } public void testPutAll() { // GenericsNote: Updating this testcase to better reflect the type safety of the new CaseInsensitiveMap Map map = new HashMap(); map.put("One", "One"); map.put("Two", "Two"); map.put("one", "Three"); map.put(null, "Four"); //map.put(new Integer(20), "Five"); Map caseInsensitiveMap = new CaseInsensitiveMap(map); assertTrue(caseInsensitiveMap.size() == 3); // ones collapsed Set keys = caseInsensitiveMap.keySet(); assertTrue(keys.contains("one")); assertTrue(keys.contains("two")); assertTrue(keys.contains(null)); //assertTrue(keys.contains(Integer.toString(20))); assertTrue(keys.size() == 3); assertTrue(!caseInsensitiveMap.containsValue("One") || !caseInsensitiveMap.containsValue("Three")); // ones collaped assertEquals(caseInsensitiveMap.get(null), "Four"); } public void testClone() { CaseInsensitiveMap map = new CaseInsensitiveMap(10); map.put("1", "1"); Map cloned = (Map) map.clone(); assertEquals(map.size(), cloned.size()); assertSame(map.get("1"), cloned.get("1")); } /* public void testCreate() throws Exception { resetEmpty(); writeExternalFormToDisk((java.io.Serializable) map, "/home/phil/jakarta-commons/collections15/data/test/CaseInsensitiveMap.emptyCollection.version3.obj"); resetFull(); writeExternalFormToDisk((java.io.Serializable) map, "/home/phil/jakarta-commons/collections15/data/test/CaseInsensitiveMap.fullCollection.version3.obj"); } */ } collections-generic-4.01/src/test/org/apache/commons/collections15/map/TestLazyMap.java0000644000175000017500000000630110464140764031354 0ustar giovannigiovanni/* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.map; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.collections15.Factory; import org.apache.commons.collections15.FactoryUtils; import java.util.HashMap; import java.util.Map; /** * Extension of {@link TestMap} for exercising the * {@link LazyMap} implementation. * * @author Matt Hall, John Watkinson, Phil Steitz * @version $Revision: 1.1 $ $Date: 2005/10/11 19:11:58 $ * @since Commons Collections 3.0 */ public class TestLazyMap extends AbstractTestMap { protected static final Factory oneFactory = FactoryUtils.constantFactory("One"); protected static final Factory nullFactory = FactoryUtils.nullFactory(); public TestLazyMap(String testName) { super(testName); } public static Test suite() { return new TestSuite(TestLazyMap.class); } public static void main(String args[]) { String[] testCaseName = {TestLazyMap.class.getName()}; junit.textui.TestRunner.main(testCaseName); } //----------------------------------------------------------------------- protected Map decorateMap(Map map, Factory factory) { return LazyMap.decorate(map, factory); } public Map makeEmptyMap() { return decorateMap(new HashMap(), nullFactory); } protected Map makeTestMap(Factory factory) { return decorateMap(new HashMap(), factory); } //----------------------------------------------------------------------- public void testMapGet() { Map map = makeTestMap(oneFactory); assertEquals(0, map.size()); String s1 = (String) map.get("Five"); assertEquals("One", s1); assertEquals(1, map.size()); String s2 = (String) map.get(new String(new char[]{'F', 'i', 'v', 'e'})); assertEquals("One", s2); assertEquals(1, map.size()); assertSame(s1, s2); map = makeTestMap(nullFactory); Object o = map.get("Five"); assertEquals(null, o); assertEquals(1, map.size()); } public String getCompatibilityVersion() { return "3.1"; } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk( // (java.io.Serializable) map, // "D:/dev/collections15/data/test/LazyMap.emptyCollection.version3.1.obj"); // resetFull(); // writeExternalFormToDisk( // (java.io.Serializable) map, // "D:/dev/collections15/data/test/LazyMap.fullCollection.version3.1.obj"); // } }collections-generic-4.01/src/test/org/apache/commons/collections15/map/TestMultiKeyMap.java0000644000175000017500000005431010464140761032200 0ustar giovannigiovanni/* * Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.map; import junit.framework.Test; import junit.textui.TestRunner; import org.apache.commons.collections15.BulkTest; import org.apache.commons.collections15.MapIterator; import org.apache.commons.collections15.keyvalue.MultiKey; import java.util.Map; /** * JUnit tests. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 19:11:58 $ */ public class TestMultiKeyMap extends AbstractTestIterableMap { static final Integer I1 = new Integer(1); static final Integer I2 = new Integer(2); static final Integer I3 = new Integer(3); static final Integer I4 = new Integer(4); static final Integer I5 = new Integer(5); static final Integer I6 = new Integer(6); static final Integer I7 = new Integer(7); static final Integer I8 = new Integer(8); public TestMultiKeyMap(String testName) { super(testName); } public static void main(String[] args) { TestRunner.run(suite()); } public static Test suite() { return BulkTest.makeSuite(TestMultiKeyMap.class); } public Map makeEmptyMap() { return new MultiKeyMap(); } public Object[] getSampleKeys() { return getMultiKeyKeys(); } private MultiKey[] getMultiKeyKeys() { return new MultiKey[]{new MultiKey(I1, I2), new MultiKey(I2, I3), new MultiKey(I3, I4), new MultiKey(I1, I1, I2), new MultiKey(I2, I3, I4), new MultiKey(I3, I7, I6), new MultiKey(I1, I1, I2, I3), new MultiKey(I2, I4, I5, I6), new MultiKey(I3, I6, I7, I8), new MultiKey(I1, I1, I2, I3, I4), new MultiKey(I2, I3, I4, I5, I6), new MultiKey(I3, I5, I6, I7, I8), }; } public Object[] getSampleValues() { return new Object[]{"2A", "2B", "2C", "3D", "3E", "3F", "4G", "4H", "4I", "5J", "5K", "5L", }; } public Object[] getNewSampleValues() { return new Object[]{"1a", "1b", "1c", "2d", "2e", "2f", "3g", "3h", "3i", "4j", "4k", "4l", }; } public Object[] getOtherKeys() { return new Object[]{new MultiKey(I1, I7), new MultiKey(I1, I8), new MultiKey(I2, I4), new MultiKey(I2, I5), }; } public boolean isAllowNullKey() { return false; } //----------------------------------------------------------------------- public void testNullHandling() { resetFull(); assertEquals(null, map.get(null)); assertEquals(false, map.containsKey(null)); assertEquals(false, map.containsValue(null)); assertEquals(null, map.remove(null)); assertEquals(false, map.entrySet().contains(null)); assertEquals(false, map.keySet().contains(null)); assertEquals(false, map.values().contains(null)); try { map.put(null, null); fail(); } catch (NullPointerException ex) { } assertEquals(null, map.put(new MultiKey(null, null), null)); try { map.put(null, new Object()); fail(); } catch (NullPointerException ex) { } } //----------------------------------------------------------------------- public void testMultiKeyGet() { resetFull(); MultiKeyMap multimap = (MultiKeyMap) map; MultiKey[] keys = getMultiKeyKeys(); Object[] values = getSampleValues(); for (int i = 0; i < keys.length; i++) { MultiKey key = keys[i]; Object value = values[i]; switch (key.size()) { case 2: assertEquals(value, multimap.get(key.getKey(0), key.getKey(1))); assertEquals(null, multimap.get(null, key.getKey(1))); assertEquals(null, multimap.get(key.getKey(0), null)); assertEquals(null, multimap.get(null, null)); assertEquals(null, multimap.get(key.getKey(0), key.getKey(1), null)); assertEquals(null, multimap.get(key.getKey(0), key.getKey(1), null, null)); assertEquals(null, multimap.get(key.getKey(0), key.getKey(1), null, null, null)); break; case 3: assertEquals(value, multimap.get(key.getKey(0), key.getKey(1), key.getKey(2))); assertEquals(null, multimap.get(null, key.getKey(1), key.getKey(2))); assertEquals(null, multimap.get(key.getKey(0), null, key.getKey(2))); assertEquals(null, multimap.get(key.getKey(0), key.getKey(1), null)); assertEquals(null, multimap.get(null, null, null)); assertEquals(null, multimap.get(key.getKey(0), key.getKey(1), key.getKey(2), null)); assertEquals(null, multimap.get(key.getKey(0), key.getKey(1), key.getKey(2), null, null)); break; case 4: assertEquals(value, multimap.get(key.getKey(0), key.getKey(1), key.getKey(2), key.getKey(3))); assertEquals(null, multimap.get(null, key.getKey(1), key.getKey(2), key.getKey(3))); assertEquals(null, multimap.get(key.getKey(0), null, key.getKey(2), key.getKey(3))); assertEquals(null, multimap.get(key.getKey(0), key.getKey(1), null, key.getKey(3))); assertEquals(null, multimap.get(key.getKey(0), key.getKey(1), key.getKey(2), null)); assertEquals(null, multimap.get(null, null, null, null)); assertEquals(null, multimap.get(key.getKey(0), key.getKey(1), key.getKey(2), key.getKey(3), null)); break; case 5: assertEquals(value, multimap.get(key.getKey(0), key.getKey(1), key.getKey(2), key.getKey(3), key.getKey(4))); assertEquals(null, multimap.get(null, key.getKey(1), key.getKey(2), key.getKey(3), key.getKey(4))); assertEquals(null, multimap.get(key.getKey(0), null, key.getKey(2), key.getKey(3), key.getKey(4))); assertEquals(null, multimap.get(key.getKey(0), key.getKey(1), null, key.getKey(3), key.getKey(4))); assertEquals(null, multimap.get(key.getKey(0), key.getKey(1), key.getKey(2), null, key.getKey(4))); assertEquals(null, multimap.get(key.getKey(0), key.getKey(1), key.getKey(2), key.getKey(3), null)); assertEquals(null, multimap.get(null, null, null, null, null)); break; default: fail("Invalid key size"); } } } public void testMultiKeyContainsKey() { resetFull(); MultiKeyMap multimap = (MultiKeyMap) map; MultiKey[] keys = getMultiKeyKeys(); Object[] values = getSampleValues(); for (int i = 0; i < keys.length; i++) { MultiKey key = keys[i]; Object value = values[i]; switch (key.size()) { case 2: assertEquals(true, multimap.containsKey(key.getKey(0), key.getKey(1))); assertEquals(false, multimap.containsKey(null, key.getKey(1))); assertEquals(false, multimap.containsKey(key.getKey(0), null)); assertEquals(false, multimap.containsKey(null, null)); assertEquals(false, multimap.containsKey(key.getKey(0), key.getKey(1), null)); assertEquals(false, multimap.containsKey(key.getKey(0), key.getKey(1), null, null)); assertEquals(false, multimap.containsKey(key.getKey(0), key.getKey(1), null, null, null)); break; case 3: assertEquals(true, multimap.containsKey(key.getKey(0), key.getKey(1), key.getKey(2))); assertEquals(false, multimap.containsKey(null, key.getKey(1), key.getKey(2))); assertEquals(false, multimap.containsKey(key.getKey(0), null, key.getKey(2))); assertEquals(false, multimap.containsKey(key.getKey(0), key.getKey(1), null)); assertEquals(false, multimap.containsKey(null, null, null)); assertEquals(false, multimap.containsKey(key.getKey(0), key.getKey(1), key.getKey(2), null)); assertEquals(false, multimap.containsKey(key.getKey(0), key.getKey(1), key.getKey(2), null, null)); break; case 4: assertEquals(true, multimap.containsKey(key.getKey(0), key.getKey(1), key.getKey(2), key.getKey(3))); assertEquals(false, multimap.containsKey(null, key.getKey(1), key.getKey(2), key.getKey(3))); assertEquals(false, multimap.containsKey(key.getKey(0), null, key.getKey(2), key.getKey(3))); assertEquals(false, multimap.containsKey(key.getKey(0), key.getKey(1), null, key.getKey(3))); assertEquals(false, multimap.containsKey(key.getKey(0), key.getKey(1), key.getKey(2), null)); assertEquals(false, multimap.containsKey(null, null, null, null)); assertEquals(false, multimap.containsKey(key.getKey(0), key.getKey(1), key.getKey(2), key.getKey(3), null)); break; case 5: assertEquals(true, multimap.containsKey(key.getKey(0), key.getKey(1), key.getKey(2), key.getKey(3), key.getKey(4))); assertEquals(false, multimap.containsKey(null, key.getKey(1), key.getKey(2), key.getKey(3), key.getKey(4))); assertEquals(false, multimap.containsKey(key.getKey(0), null, key.getKey(2), key.getKey(3), key.getKey(4))); assertEquals(false, multimap.containsKey(key.getKey(0), key.getKey(1), null, key.getKey(3), key.getKey(4))); assertEquals(false, multimap.containsKey(key.getKey(0), key.getKey(1), key.getKey(2), null, key.getKey(4))); assertEquals(false, multimap.containsKey(key.getKey(0), key.getKey(1), key.getKey(2), key.getKey(3), null)); assertEquals(false, multimap.containsKey(null, null, null, null, null)); break; default: fail("Invalid key size"); } } } protected int hash(Object key1, Object key2) { int h = 0; if (key1 != null) { h ^= key1.hashCode(); } if (key2 != null) { h ^= key2.hashCode(); } h += ~(h << 9); h ^= (h >>> 14); h += (h << 4); h ^= (h >>> 10); return h; } public void testMultiKeyPut() { MultiKey[] keys = getMultiKeyKeys(); Object[] values = getSampleValues(); for (int i = 0; i < keys.length; i++) { MultiKeyMap multimap = new MultiKeyMap(); MultiKey key = keys[i]; Object value = values[i]; int oldkey = hash(key.getKey(0), key.getKey(1)); switch (key.size()) { case 2: assertEquals(null, multimap.put(key.getKey(0), key.getKey(1), value)); assertEquals(1, multimap.size()); assertEquals(value, multimap.get(key.getKey(0), key.getKey(1))); assertEquals(true, multimap.containsKey(key.getKey(0), key.getKey(1))); assertEquals(true, multimap.containsKey(new MultiKey(key.getKey(0), key.getKey(1)))); assertEquals(value, multimap.put(key.getKey(0), key.getKey(1), null)); assertEquals(1, multimap.size()); assertEquals(null, multimap.get(key.getKey(0), key.getKey(1))); assertEquals(true, multimap.containsKey(key.getKey(0), key.getKey(1))); break; case 3: assertEquals(null, multimap.put(key.getKey(0), key.getKey(1), key.getKey(2), value)); assertEquals(1, multimap.size()); assertEquals(value, multimap.get(key.getKey(0), key.getKey(1), key.getKey(2))); assertEquals(true, multimap.containsKey(key.getKey(0), key.getKey(1), key.getKey(2))); assertEquals(true, multimap.containsKey(new MultiKey(key.getKey(0), key.getKey(1), key.getKey(2)))); assertEquals(value, multimap.put(key.getKey(0), key.getKey(1), key.getKey(2), null)); assertEquals(1, multimap.size()); assertEquals(null, multimap.get(key.getKey(0), key.getKey(1), key.getKey(2))); assertEquals(true, multimap.containsKey(key.getKey(0), key.getKey(1), key.getKey(2))); break; case 4: assertEquals(null, multimap.put(key.getKey(0), key.getKey(1), key.getKey(2), key.getKey(3), value)); assertEquals(1, multimap.size()); assertEquals(value, multimap.get(key.getKey(0), key.getKey(1), key.getKey(2), key.getKey(3))); assertEquals(true, multimap.containsKey(key.getKey(0), key.getKey(1), key.getKey(2), key.getKey(3))); assertEquals(true, multimap.containsKey(new MultiKey(key.getKey(0), key.getKey(1), key.getKey(2), key.getKey(3)))); assertEquals(value, multimap.put(key.getKey(0), key.getKey(1), key.getKey(2), key.getKey(3), null)); assertEquals(1, multimap.size()); assertEquals(null, multimap.get(key.getKey(0), key.getKey(1), key.getKey(2), key.getKey(3))); assertEquals(true, multimap.containsKey(key.getKey(0), key.getKey(1), key.getKey(2), key.getKey(3))); break; case 5: assertEquals(null, multimap.put(key.getKey(0), key.getKey(1), key.getKey(2), key.getKey(3), key.getKey(4), value)); assertEquals(1, multimap.size()); assertEquals(value, multimap.get(key.getKey(0), key.getKey(1), key.getKey(2), key.getKey(3), key.getKey(4))); assertEquals(true, multimap.containsKey(key.getKey(0), key.getKey(1), key.getKey(2), key.getKey(3), key.getKey(4))); assertEquals(true, multimap.containsKey(new MultiKey(key.getKey(0), key.getKey(1), key.getKey(2), key.getKey(3), key.getKey(4)))); assertEquals(value, multimap.put(key.getKey(0), key.getKey(1), key.getKey(2), key.getKey(3), key.getKey(4), null)); assertEquals(1, multimap.size()); assertEquals(null, multimap.get(key.getKey(0), key.getKey(1), key.getKey(2), key.getKey(3), key.getKey(4))); assertEquals(true, multimap.containsKey(key.getKey(0), key.getKey(1), key.getKey(2), key.getKey(3), key.getKey(4))); break; default: fail("Invalid key size"); } } } public void testMultiKeyRemove() { MultiKey[] keys = getMultiKeyKeys(); Object[] values = getSampleValues(); for (int i = 0; i < keys.length; i++) { resetFull(); MultiKeyMap multimap = (MultiKeyMap) map; int size = multimap.size(); MultiKey key = keys[i]; Object value = values[i]; switch (key.size()) { case 2: assertEquals(true, multimap.containsKey(key.getKey(0), key.getKey(1))); assertEquals(value, multimap.remove(key.getKey(0), key.getKey(1))); assertEquals(false, multimap.containsKey(key.getKey(0), key.getKey(1))); assertEquals(size - 1, multimap.size()); assertEquals(null, multimap.remove(key.getKey(0), key.getKey(1))); assertEquals(false, multimap.containsKey(key.getKey(0), key.getKey(1))); break; case 3: assertEquals(true, multimap.containsKey(key.getKey(0), key.getKey(1), key.getKey(2))); assertEquals(value, multimap.remove(key.getKey(0), key.getKey(1), key.getKey(2))); assertEquals(false, multimap.containsKey(key.getKey(0), key.getKey(1), key.getKey(2))); assertEquals(size - 1, multimap.size()); assertEquals(null, multimap.remove(key.getKey(0), key.getKey(1), key.getKey(2))); assertEquals(false, multimap.containsKey(key.getKey(0), key.getKey(1), key.getKey(2))); break; case 4: assertEquals(true, multimap.containsKey(key.getKey(0), key.getKey(1), key.getKey(2), key.getKey(3))); assertEquals(value, multimap.remove(key.getKey(0), key.getKey(1), key.getKey(2), key.getKey(3))); assertEquals(false, multimap.containsKey(key.getKey(0), key.getKey(1), key.getKey(2), key.getKey(3))); assertEquals(size - 1, multimap.size()); assertEquals(null, multimap.remove(key.getKey(0), key.getKey(1), key.getKey(2), key.getKey(3))); assertEquals(false, multimap.containsKey(key.getKey(0), key.getKey(1), key.getKey(2), key.getKey(3))); break; case 5: assertEquals(true, multimap.containsKey(key.getKey(0), key.getKey(1), key.getKey(2), key.getKey(3), key.getKey(4))); assertEquals(value, multimap.remove(key.getKey(0), key.getKey(1), key.getKey(2), key.getKey(3), key.getKey(4))); assertEquals(false, multimap.containsKey(key.getKey(0), key.getKey(1), key.getKey(2), key.getKey(3), key.getKey(4))); assertEquals(size - 1, multimap.size()); assertEquals(null, multimap.remove(key.getKey(0), key.getKey(1), key.getKey(2), key.getKey(3), key.getKey(4))); assertEquals(false, multimap.containsKey(key.getKey(0), key.getKey(1), key.getKey(2), key.getKey(3), key.getKey(4))); break; default: fail("Invalid key size"); } } } public void testMultiKeyRemoveAll1() { resetFull(); MultiKeyMap multimap = (MultiKeyMap) map; assertEquals(12, multimap.size()); multimap.removeAll(I1); assertEquals(8, multimap.size()); for (MapIterator it = multimap.mapIterator(); it.hasNext();) { MultiKey key = (MultiKey) it.next(); assertEquals(false, I1.equals(key.getKey(0))); } } public void testMultiKeyRemoveAll2() { resetFull(); MultiKeyMap multimap = (MultiKeyMap) map; assertEquals(12, multimap.size()); multimap.removeAll(I2, I3); assertEquals(9, multimap.size()); for (MapIterator it = multimap.mapIterator(); it.hasNext();) { MultiKey key = (MultiKey) it.next(); assertEquals(false, I2.equals(key.getKey(0)) && I3.equals(key.getKey(1))); } } public void testMultiKeyRemoveAll3() { resetFull(); MultiKeyMap multimap = (MultiKeyMap) map; assertEquals(12, multimap.size()); multimap.removeAll(I1, I1, I2); assertEquals(9, multimap.size()); for (MapIterator it = multimap.mapIterator(); it.hasNext();) { MultiKey key = (MultiKey) it.next(); assertEquals(false, I1.equals(key.getKey(0)) && I1.equals(key.getKey(1)) && I2.equals(key.getKey(2))); } } public void testMultiKeyRemoveAll4() { resetFull(); MultiKeyMap multimap = (MultiKeyMap) map; assertEquals(12, multimap.size()); multimap.removeAll(I1, I1, I2, I3); assertEquals(10, multimap.size()); for (MapIterator it = multimap.mapIterator(); it.hasNext();) { MultiKey key = (MultiKey) it.next(); assertEquals(false, I1.equals(key.getKey(0)) && I1.equals(key.getKey(1)) && I2.equals(key.getKey(2)) && key.size() >= 4 && I3.equals(key.getKey(3))); } } //----------------------------------------------------------------------- public void testClone() { MultiKeyMap map = new MultiKeyMap(); map.put(new MultiKey(I1, I2), "1-2"); Map cloned = (Map) map.clone(); assertEquals(map.size(), cloned.size()); assertSame(map.get(new MultiKey(I1, I2)), cloned.get(new MultiKey(I1, I2))); } //----------------------------------------------------------------------- public void testLRUMultiKeyMap() { MultiKeyMap map = MultiKeyMap.decorate(new LRUMap(2)); map.put(I1, I2, "1-2"); map.put(I1, I3, "1-3"); assertEquals(2, map.size()); map.put(I1, I4, "1-4"); assertEquals(2, map.size()); assertEquals(true, map.containsKey(I1, I3)); assertEquals(true, map.containsKey(I1, I4)); assertEquals(false, map.containsKey(I1, I2)); MultiKeyMap cloned = (MultiKeyMap) map.clone(); assertEquals(2, map.size()); assertEquals(true, cloned.containsKey(I1, I3)); assertEquals(true, cloned.containsKey(I1, I4)); assertEquals(false, cloned.containsKey(I1, I2)); cloned.put(I1, I5, "1-5"); assertEquals(2, cloned.size()); assertEquals(true, cloned.containsKey(I1, I4)); assertEquals(true, cloned.containsKey(I1, I5)); } //----------------------------------------------------------------------- public String getCompatibilityVersion() { return "3.1"; } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk( // (java.io.Serializable) map, // "D:/dev/collections15/data/test/MultiKeyMap.emptyCollection.version3.1.obj"); // resetFull(); // writeExternalFormToDisk( // (java.io.Serializable) map, // "D:/dev/collections15/data/test/MultiKeyMap.fullCollection.version3.1.obj"); // } } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootcollections-generic-4.01/src/test/org/apache/commons/collections15/map/TestUnmodifiableSortedMap.javacollections-generic-4.01/src/test/org/apache/commons/collections15/map/TestUnmodifiableSortedMap.jav0000644000175000017500000000627110464140762034057 0ustar giovannigiovanni/* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.map; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.collections15.Unmodifiable; import java.util.Map; import java.util.SortedMap; import java.util.TreeMap; /** * Extension of {@link AbstractTestSortedMap} for exercising the * {@link UnmodifiableSortedMap} implementation. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:06:04 $ * @since Commons Collections 3.0 */ public class TestUnmodifiableSortedMap extends AbstractTestSortedMap { public TestUnmodifiableSortedMap(String testName) { super(testName); } public static Test suite() { return new TestSuite(TestUnmodifiableSortedMap.class); } public static void main(String args[]) { String[] testCaseName = {TestUnmodifiableSortedMap.class.getName()}; junit.textui.TestRunner.main(testCaseName); } //------------------------------------------------------------------- public Map makeEmptyMap() { return UnmodifiableSortedMap.decorate(new TreeMap()); } public boolean isPutChangeSupported() { return false; } public boolean isPutAddSupported() { return false; } public boolean isRemoveSupported() { return false; } public Map makeFullMap() { SortedMap m = new TreeMap(); addSampleMappings(m); return UnmodifiableSortedMap.decorate(m); } //----------------------------------------------------------------------- public void testUnmodifiable() { assertTrue(makeEmptyMap() instanceof Unmodifiable); assertTrue(makeFullMap() instanceof Unmodifiable); } public void testDecorateFactory() { Map map = makeFullMap(); assertSame(map, UnmodifiableSortedMap.decorate((SortedMap) map)); try { UnmodifiableSortedMap.decorate(null); fail(); } catch (IllegalArgumentException ex) { } } public String getCompatibilityVersion() { return "3.1"; } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk( // (java.io.Serializable) map, // "D:/dev/collections15/data/test/UnmodifiableSortedMap.emptyCollection.version3.1.obj"); // resetFull(); // writeExternalFormToDisk( // (java.io.Serializable) map, // "D:/dev/collections15/data/test/UnmodifiableSortedMap.fullCollection.version3.1.obj"); // } }collections-generic-4.01/src/test/org/apache/commons/collections15/map/AbstractTestMultiMap.java0000644000175000017500000016532410464140761033223 0ustar giovannigiovanni/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.map; import org.apache.commons.collections15.AbstractTestObject; import org.apache.commons.collections15.BulkTest; import org.apache.commons.collections15.MultiMap; import org.apache.commons.collections15.multimap.MultiHashMap; import org.apache.commons.collections15.collection.AbstractTestCollection; import org.apache.commons.collections15.set.AbstractTestSet; import java.util.*; /** * Abstract test class for {@link java.util.Map} methods and contracts. *

                  * The forces at work here are similar to those in {@link org.apache.commons.collections15.collection.AbstractTestCollection}. * If your class implements the full Map interface, including optional * operations, simply extend this class, and implement the * {@link #makeEmptyMap()} method. *

                  * On the other hand, if your map implementation is weird, you may have to * override one or more of the other protected methods. They're described * below. *

                  * Entry Population Methods *

                  * Override these methods if your map requires special entries: *

                  *

                    *
                  • {@link #getSampleKeys()} *
                  • {@link #getSampleValues()} *
                  • {@link #getNewSampleValues()} *
                  • {@link #getOtherKeys()} *
                  • {@link #getOtherValues()} *
                  *

                  * Supported Operation Methods *

                  * Override these methods if your map doesn't support certain operations: *

                  *

                    *
                  • {@link #isPutAddSupported()} *
                  • {@link #isPutChangeSupported()} *
                  • {@link #isSetValueSupported()} *
                  • {@link #isRemoveSupported()} *
                  • {@link #isGetStructuralModify()} *
                  • {@link #isAllowDuplicateValues()} *
                  • {@link #isAllowNullKey()} *
                  • {@link #isAllowNullValue()} *
                  *

                  * Fixture Methods *

                  * For tests on modification operations (puts and removes), fixtures are used * to verify that that operation results in correct state for the map and its * collection views. Basically, the modification is performed against your * map implementation, and an identical modification is performed against * a confirmed map implementation. A confirmed map implementation is * something like java.util.HashMap, which is known to conform * exactly to the {@link java.util.Map} contract. After the modification takes place * on both your map implementation and the confirmed map implementation, the * two maps are compared to see if their state is identical. The comparison * also compares the collection views to make sure they're still the same.

                  *

                  * The upshot of all that is that any test that modifies the map in * any way will verify that all of the map's state is still * correct, including the state of its collection views. So for instance * if a key is removed by the map's key set's iterator, then the entry set * is checked to make sure the key/value pair no longer appears.

                  *

                  * The {@link #map} field holds an instance of your collection implementation. * The {@link #entrySet}, {@link #keySet} and {@link #values} fields hold * that map's collection views. And the {@link #confirmed} field holds * an instance of the confirmed collection implementation. The * {@link #resetEmpty()} and {@link #resetFull()} methods set these fields to * empty or full maps, so that tests can proceed from a known state.

                  *

                  * After a modification operation to both {@link #map} and {@link #confirmed}, * the {@link #verify()} method is invoked to compare the results. The * {@link #verify} method calls separate methods to verify the map and its three * collection views ({@link #verifyMap}, {@link #verifyEntrySet}, * {@link #verifyKeySet}, and {@link #verifyValues}). You may want to override * one of the verification methodsto perform additional verifications. For * instance, TestDoubleOrderedMap would want override its * {@link #verifyValues()} method to verify that the values are unique and in * ascending order.

                  *

                  * Other Notes *

                  * If your {@link java.util.Map} fails one of these tests by design, you may still use * this base set of cases. Simply override the test case (method) your map * fails and/or the methods that define the assumptions used by the test * cases. For example, if your map does not allow duplicate values, override * {@link #isAllowDuplicateValues()} and have it return false * * @author Michael Smith * @author Rodney Waldhoff * @author Paul Jack * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 19:11:58 $ */ public abstract class AbstractTestMultiMap extends AbstractTestObject { /** * JDK1.2 has bugs in null handling of Maps, especially HashMap.Entry.toString * This avoids nulls for JDK1.2 */ private static final boolean JDK12; static { String str = System.getProperty("java.version"); JDK12 = str.startsWith("1.2"); } // These instance variables are initialized with the reset method. // Tests for map methods that alter the map (put, putAll, remove) // first call reset() to create the map and its views; then perform // the modification on the map; perform the same modification on the // confirmed; and then call verify() to ensure that the map is equal // to the confirmed, that the already-constructed collection views // are still equal to the confirmed's collection views. /** * Map created by reset(). */ protected MultiMap map; /** * Entry set of map created by reset(). */ protected Set entrySet; /** * Key set of map created by reset(). */ protected Set keySet; /** * Values collection of map created by reset(). */ protected Collection values; /** * HashMap created by reset(). */ protected MultiMap confirmed; /** * JUnit constructor. * * @param testName the test name */ public AbstractTestMultiMap(String testName) { super(testName); } /** * Returns true if the maps produced by * {@link #makeEmptyMap()} and {@link #makeFullMap()} * support the put and putAll operations * adding new mappings. *

                  * Default implementation returns true. * Override if your collection class does not support put adding. */ public boolean isPutAddSupported() { return true; } /** * Returns true if the maps produced by * {@link #makeEmptyMap()} and {@link #makeFullMap()} * support the put and putAll operations * changing existing mappings. *

                  * Default implementation returns true. * Override if your collection class does not support put changing. */ public boolean isPutChangeSupported() { return true; } /** * Returns true if the maps produced by * {@link #makeEmptyMap()} and {@link #makeFullMap()} * support the setValue operation on entrySet entries. *

                  * Default implementation returns isPutChangeSupported(). * Override if your collection class does not support setValue but does * support put changing. */ public boolean isSetValueSupported() { return isPutChangeSupported(); } /** * Returns true if the maps produced by * {@link #makeEmptyMap()} and {@link #makeFullMap()} * support the remove and clear operations. *

                  * Default implementation returns true. * Override if your collection class does not support removal operations. */ public boolean isRemoveSupported() { return true; } /** * Returns true if the maps produced by * {@link #makeEmptyMap()} and {@link #makeFullMap()} * can cause structural modification on a get(). The example is LRUMap. *

                  * Default implementation returns false. * Override if your map class structurally modifies on get. */ public boolean isGetStructuralModify() { return false; } /** * Returns whether the sub map views of SortedMap are serializable. * If the class being tested is based around a TreeMap then you should * override and return false as TreeMap has a bug in deserialization. * * @return false */ public boolean isSubMapViewsSerializable() { return true; } /** * Returns true if the maps produced by * {@link #makeEmptyMap()} and {@link #makeFullMap()} * supports null keys. *

                  * Default implementation returns true. * Override if your collection class does not support null keys. */ public boolean isAllowNullKey() { return true; } /** * Returns true if the maps produced by * {@link #makeEmptyMap()} and {@link #makeFullMap()} * supports null values. *

                  * Default implementation returns true. * Override if your collection class does not support null values. */ public boolean isAllowNullValue() { return true; } /** * Returns true if the maps produced by * {@link #makeEmptyMap()} and {@link #makeFullMap()} * supports duplicate values. *

                  * Default implementation returns true. * Override if your collection class does not support duplicate values. */ public boolean isAllowDuplicateValues() { return true; } /** * Returns the set of keys in the mappings used to test the map. This * method must return an array with the same length as {@link * #getSampleValues()} and all array elements must be different. The * default implementation constructs a set of String keys, and includes a * single null key if {@link #isAllowNullKey()} returns true. */ public Object[] getSampleKeys() { Object[] result = new Object[]{"blah", "foo", "bar", "baz", "tmp", "gosh", "golly", "gee", "hello", "goodbye", "we'll", "see", "you", "all", "again", "key", "key2", (isAllowNullKey() && !JDK12) ? null : "nonnullkey"}; return result; } public Object[] getOtherKeys() { return getOtherNonNullStringElements(); } public Object[] getOtherValues() { return getOtherNonNullStringElements(); } /** * Returns a list of string elements suitable for return by * {@link #getOtherKeys()} or {@link #getOtherValues}. *

                  *

                  Override getOtherElements to returnthe results of this method if your * collection does not support heterogenous elements or the null element. *

                  */ public Object[] getOtherNonNullStringElements() { return new Object[]{"For", "then", "despite", /* of */"space", "I", "would", "be", "brought", "From", "limits", "far", "remote", "where", "thou", "dost", "stay"}; } /** * Returns the set of values in the mappings used to test the map. This * method must return an array with the same length as * {@link #getSampleKeys()}. The default implementation constructs a set of * String values and includes a single null value if * {@link #isAllowNullValue()} returns true, and includes * two values that are the same if {@link #isAllowDuplicateValues()} returns * true. */ public Object[] getSampleValues() { Object[] result = new Object[]{"blahv", "foov", "barv", "bazv", "tmpv", "goshv", "gollyv", "geev", "hellov", "goodbyev", "we'llv", "seev", "youv", "allv", "againv", (isAllowNullValue() && !JDK12) ? null : "nonnullvalue", "value", (isAllowDuplicateValues()) ? "value" : "value2", }; return result; } /** * Returns a the set of values that can be used to replace the values * returned from {@link #getSampleValues()}. This method must return an * array with the same length as {@link #getSampleValues()}. The values * returned from this method should not be the same as those returned from * {@link #getSampleValues()}. The default implementation constructs a * set of String values and includes a single null value if * {@link #isAllowNullValue()} returns true, and includes two values * that are the same if {@link #isAllowDuplicateValues()} returns * true. */ public Object[] getNewSampleValues() { Object[] result = new Object[]{(isAllowNullValue() && !JDK12 && isAllowDuplicateValues()) ? null : "newnonnullvalue", "newvalue", (isAllowDuplicateValues()) ? "newvalue" : "newvalue2", "newblahv", "newfoov", "newbarv", "newbazv", "newtmpv", "newgoshv", "newgollyv", "newgeev", "newhellov", "newgoodbyev", "newwe'llv", "newseev", "newyouv", "newallv", "newagainv", }; return result; } /** * Helper method to add all the mappings described by * {@link #getSampleKeys()} and {@link #getSampleValues()}. */ public void addSampleMappings(MultiMap m) { Object[] keys = getSampleKeys(); Object[] values = getSampleValues(); for (int i = 0; i < keys.length; i++) { try { m.put(keys[i], values[i]); } catch (NullPointerException exception) { assertTrue("NullPointerException only allowed to be thrown " + "if either the key or value is null.", keys[i] == null || values[i] == null); assertTrue("NullPointerException on null key, but " + "isAllowNullKey is not overridden to return false.", keys[i] == null || !isAllowNullKey()); assertTrue("NullPointerException on null value, but " + "isAllowNullValue is not overridden to return false.", values[i] == null || !isAllowNullValue()); assertTrue("Unknown reason for NullPointer.", false); } } assertEquals("size must reflect number of mappings added.", keys.length, m.size()); } //----------------------------------------------------------------------- /** * Return a new, empty {@link java.util.Map} to be used for testing. * * @return the map to be tested */ public abstract MultiMap makeEmptyMap(); /** * Return a new, populated map. The mappings in the map should match the * keys and values returned from {@link #getSampleKeys()} and * {@link #getSampleValues()}. The default implementation uses makeEmptyMap() * and calls {@link #addSampleMappings} to add all the mappings to the * map. * * @return the map to be tested */ public MultiMap makeFullMap() { MultiMap m = makeEmptyMap(); addSampleMappings(m); return m; } /** * Implements the superclass method to return the map to be tested. * * @return the map to be tested */ public Object makeObject() { return makeEmptyMap(); } /** * Override to return a map other than HashMap as the confirmed map. * * @return a map that is known to be valid */ public MultiMap makeConfirmedMap() { return new MultiHashMap(); } /** * Creates a new Map Entry that is independent of the first and the map. */ public Map.Entry cloneMapEntry(Map.Entry entry) { HashMap map = new HashMap(); map.put(entry.getKey(), entry.getValue()); return (Map.Entry) map.entrySet().iterator().next(); } /** * Gets the compatability version, needed for package access. */ public String getCompatibilityVersion() { return super.getCompatibilityVersion(); } //----------------------------------------------------------------------- /** * Test to ensure the test setup is working properly. This method checks * to ensure that the getSampleKeys and getSampleValues methods are * returning results that look appropriate. That is, they both return a * non-null array of equal length. The keys array must not have any * duplicate values, and may only contain a (single) null key if * isNullKeySupported() returns true. The values array must only have a null * value if useNullValue() is true and may only have duplicate values if * isAllowDuplicateValues() returns true. */ public void testSampleMappings() { Object[] keys = getSampleKeys(); Object[] values = getSampleValues(); Object[] newValues = getNewSampleValues(); assertTrue("failure in test: Must have keys returned from " + "getSampleKeys.", keys != null); assertTrue("failure in test: Must have values returned from " + "getSampleValues.", values != null); // verify keys and values have equivalent lengths (in case getSampleX are // overridden) assertEquals("failure in test: not the same number of sample " + "keys and values.", keys.length, values.length); assertEquals("failure in test: not the same number of values and new values.", values.length, newValues.length); // verify there aren't duplicate keys, and check values for (int i = 0; i < keys.length - 1; i++) { for (int j = i + 1; j < keys.length; j++) { assertTrue("failure in test: duplicate null keys.", (keys[i] != null || keys[j] != null)); assertTrue("failure in test: duplicate non-null key.", (keys[i] == null || keys[j] == null || (!keys[i].equals(keys[j]) && !keys[j].equals(keys[i])))); } assertTrue("failure in test: found null key, but isNullKeySupported " + "is false.", keys[i] != null || isAllowNullKey()); assertTrue("failure in test: found null value, but isNullValueSupported " + "is false.", values[i] != null || isAllowNullValue()); assertTrue("failure in test: found null new value, but isNullValueSupported " + "is false.", newValues[i] != null || isAllowNullValue()); assertTrue("failure in test: values should not be the same as new value", values[i] != newValues[i] && (values[i] == null || !values[i].equals(newValues[i]))); } } // tests begin here. Each test adds a little bit of tested functionality. // Many methods assume previous methods passed. That is, they do not // exhaustively recheck things that have already been checked in a previous // test methods. /** * Test to ensure that makeEmptyMap and makeFull returns a new non-null * map with each invocation. */ public void testMakeMap() { MultiMap em = makeEmptyMap(); assertTrue("failure in test: makeEmptyMap must return a non-null map.", em != null); MultiMap em2 = makeEmptyMap(); assertTrue("failure in test: makeEmptyMap must return a non-null map.", em != null); assertTrue("failure in test: makeEmptyMap must return a new map " + "with each invocation.", em != em2); MultiMap fm = makeFullMap(); assertTrue("failure in test: makeFullMap must return a non-null map.", fm != null); MultiMap fm2 = makeFullMap(); assertTrue("failure in test: makeFullMap must return a non-null map.", fm != null); assertTrue("failure in test: makeFullMap must return a new map " + "with each invocation.", fm != fm2); } /** * Tests Map.isEmpty() */ public void testMapIsEmpty() { resetEmpty(); assertEquals("Map.isEmpty() should return true with an empty map", true, map.isEmpty()); verify(); resetFull(); assertEquals("Map.isEmpty() should return false with a non-empty map", false, map.isEmpty()); verify(); } /** * Tests Map.size() */ public void testMapSize() { resetEmpty(); assertEquals("Map.size() should be 0 with an empty map", 0, map.size()); verify(); resetFull(); assertEquals("Map.size() should equal the number of entries " + "in the map", getSampleKeys().length, map.size()); verify(); } /** * Tests {@link java.util.Map#clear()}. If the map {@link #isRemoveSupported()} * can add and remove elements}, then {@link java.util.Map#size()} and * {@link java.util.Map#isEmpty()} are used to ensure that map has no elements after * a call to clear. If the map does not support adding and removing * elements, this method checks to ensure clear throws an * UnsupportedOperationException. */ public void testMapClear() { if (!isRemoveSupported()) { try { resetFull(); map.clear(); fail("Expected UnsupportedOperationException on clear"); } catch (UnsupportedOperationException ex) { } return; } resetEmpty(); map.clear(); confirmed.clear(); verify(); resetFull(); map.clear(); confirmed.clear(); verify(); } /** * Tests Map.containsKey(Object) by verifying it returns false for all * sample keys on a map created using an empty map and returns true for * all sample keys returned on a full map. */ public void testMapContainsKey() { Object[] keys = getSampleKeys(); resetEmpty(); for (int i = 0; i < keys.length; i++) { assertTrue("Map must not contain key when map is empty", !map.containsKey(keys[i])); } verify(); resetFull(); for (int i = 0; i < keys.length; i++) { assertTrue("Map must contain key for a mapping in the map. " + "Missing: " + keys[i], map.containsKey(keys[i])); } verify(); } /** * Tests Map.containsValue(Object) by verifying it returns false for all * sample values on an empty map and returns true for all sample values on * a full map. */ public void testMapContainsValue() { Object[] values = getSampleValues(); resetEmpty(); for (int i = 0; i < values.length; i++) { assertTrue("Empty map must not contain value", !map.containsValue(values[i])); } verify(); resetFull(); for (int i = 0; i < values.length; i++) { assertTrue("Map must contain value for a mapping in the map.", map.containsValue(values[i])); } verify(); } /** * Tests Map.equals(Object) */ public void testMapEquals() { resetEmpty(); assertTrue("Empty maps unequal.", map.equals(confirmed)); verify(); resetFull(); assertTrue("Full maps unequal.", map.equals(confirmed)); verify(); resetFull(); // modify the HashMap created from the full map and make sure this // change results in map.equals() to return false. Iterator iter = confirmed.keySet().iterator(); iter.next(); iter.remove(); assertTrue("Different maps equal.", !map.equals(confirmed)); resetFull(); assertTrue("equals(null) returned true.", !map.equals(null)); assertTrue("equals(new Object()) returned true.", !map.equals(new Object())); verify(); } /** * Tests Map.get(Object) */ public void testMapGet() { resetEmpty(); Object[] keys = getSampleKeys(); Object[] values = getSampleValues(); for (int i = 0; i < keys.length; i++) { assertTrue("Empty map.get() should return null.", map.get(keys[i]) == null); } verify(); resetFull(); for (int i = 0; i < keys.length; i++) { assertEquals("Full map.get() should return value from mapping.", values[i], map.get(keys[i])); } } /** * Tests Map.hashCode() */ public void testMapHashCode() { resetEmpty(); assertTrue("Empty maps have different hashCodes.", map.hashCode() == confirmed.hashCode()); resetFull(); assertTrue("Equal maps have different hashCodes.", map.hashCode() == confirmed.hashCode()); } /** * Tests Map.toString(). Since the format of the string returned by the * toString() method is not defined in the Map interface, there is no * common way to test the results of the toString() method. Thereforce, * it is encouraged that Map implementations override this test with one * that checks the format matches any format defined in its API. This * default implementation just verifies that the toString() method does * not return null. */ public void testMapToString() { resetEmpty(); assertTrue("Empty map toString() should not return null", map.toString() != null); verify(); resetFull(); assertTrue("Empty map toString() should not return null", map.toString() != null); verify(); } /** * Compare the current serialized form of the Map * against the canonical version in CVS. */ public void testEmptyMapCompatibility() throws Exception { /** * Create canonical objects with this code Map map = makeEmptyMap(); if (!(map instanceof Serializable)) return; writeExternalFormToDisk((Serializable) map, getCanonicalEmptyCollectionName(map)); */ // test to make sure the canonical form has been preserved // GenericsNote: Serialized compatibility with older class versions is not supported for now //Map map = makeEmptyMap(); //if (map instanceof Serializable && !skipSerializedCanonicalTests() && isTestSerialization()) { // Map map2 = (Map) readExternalFormFromDisk(getCanonicalEmptyCollectionName(map)); // assertEquals("Map is empty", 0, map2.size()); //} } /** * Compare the current serialized form of the Map * against the canonical version in CVS. */ public void testFullMapCompatibility() throws Exception { /** * Create canonical objects with this code Map map = makeFullMap(); if (!(map instanceof Serializable)) return; writeExternalFormToDisk((Serializable) map, getCanonicalFullCollectionName(map)); */ // test to make sure the canonical form has been preserved // GenericsNote: Serialized compatibility with older class versions is not supported for now //Map map = makeFullMap(); //if (map instanceof Serializable && !skipSerializedCanonicalTests() && isTestSerialization()) { // Map map2 = (Map) readExternalFormFromDisk(getCanonicalFullCollectionName(map)); // assertEquals("Map is the right size", getSampleKeys().length, map2.size()); //} } /** * Tests Map.put(Object, Object) */ public void testMapPut() { resetEmpty(); Object[] keys = getSampleKeys(); Object[] values = getSampleValues(); Object[] newValues = getNewSampleValues(); if (isPutAddSupported()) { for (int i = 0; i < keys.length; i++) { Object o = map.put(keys[i], values[i]); confirmed.put(keys[i], values[i]); verify(); assertTrue("First map.put should return null", o == null); assertTrue("Map should contain key after put", map.containsKey(keys[i])); assertTrue("Map should contain value after put", map.containsValue(values[i])); } if (isPutChangeSupported()) { for (int i = 0; i < keys.length; i++) { Object o = map.put(keys[i], newValues[i]); confirmed.put(keys[i], newValues[i]); verify(); assertEquals("Map.put should return previous value when changed", values[i], o); assertTrue("Map should still contain key after put when changed", map.containsKey(keys[i])); assertTrue("Map should contain new value after put when changed", map.containsValue(newValues[i])); // if duplicates are allowed, we're not guaranteed that the value // no longer exists, so don't try checking that. if (!isAllowDuplicateValues()) { assertTrue("Map should not contain old value after put when changed", !map.containsValue(values[i])); } } } else { try { // two possible exception here, either valid map.put(keys[0], newValues[0]); fail("Expected IllegalArgumentException or UnsupportedOperationException on put (change)"); } catch (IllegalArgumentException ex) { } catch (UnsupportedOperationException ex) { } } } else if (isPutChangeSupported()) { resetEmpty(); try { map.put(keys[0], values[0]); fail("Expected UnsupportedOperationException or IllegalArgumentException on put (add) when fixed size"); } catch (IllegalArgumentException ex) { } catch (UnsupportedOperationException ex) { } resetFull(); int i = 0; for (Iterator it = map.keySet().iterator(); it.hasNext() && i < newValues.length; i++) { Object key = it.next(); Object o = map.put(key, newValues[i]); Object value = confirmed.put(key, newValues[i]); verify(); assertEquals("Map.put should return previous value when changed", value, o); assertTrue("Map should still contain key after put when changed", map.containsKey(key)); assertTrue("Map should contain new value after put when changed", map.containsValue(newValues[i])); // if duplicates are allowed, we're not guaranteed that the value // no longer exists, so don't try checking that. if (!isAllowDuplicateValues()) { assertTrue("Map should not contain old value after put when changed", !map.containsValue(values[i])); } } } else { try { map.put(keys[0], values[0]); fail("Expected UnsupportedOperationException on put (add)"); } catch (UnsupportedOperationException ex) { } } } /** * Tests Map.put(null, value) */ public void testMapPutNullKey() { resetFull(); Object[] values = getSampleValues(); if (isPutAddSupported()) { if (isAllowNullKey()) { map.put(null, values[0]); } else { try { map.put(null, values[0]); fail("put(null, value) should throw NPE/IAE"); } catch (NullPointerException ex) { } catch (IllegalArgumentException ex) { } } } } /** * Tests Map.put(null, value) */ public void testMapPutNullValue() { resetFull(); Object[] keys = getSampleKeys(); if (isPutAddSupported()) { if (isAllowNullValue()) { map.put(keys[0], null); } else { try { map.put(keys[0], null); fail("put(key, null) should throw NPE/IAE"); } catch (NullPointerException ex) { } catch (IllegalArgumentException ex) { } } } } /** * Tests Map.putAll(map) */ public void testMapPutAll() { if (!isPutAddSupported()) { if (!isPutChangeSupported()) { MultiMap temp = makeFullMap(); resetEmpty(); try { map.putAll(temp); fail("Expected UnsupportedOperationException on putAll"); } catch (UnsupportedOperationException ex) { } } return; } resetEmpty(); MultiMap m2 = makeFullMap(); map.putAll(m2); confirmed.putAll(m2); verify(); resetEmpty(); m2 = makeConfirmedMap(); Object[] keys = getSampleKeys(); Object[] values = getSampleValues(); for (int i = 0; i < keys.length; i++) { m2.put(keys[i], values[i]); } map.putAll(m2); confirmed.putAll(m2); verify(); } /** * Tests Map.remove(Object) */ public void testMapRemove() { if (!isRemoveSupported()) { try { resetFull(); map.remove(map.keySet().iterator().next()); fail("Expected UnsupportedOperationException on remove"); } catch (UnsupportedOperationException ex) { } return; } resetEmpty(); Object[] keys = getSampleKeys(); Object[] values = getSampleValues(); for (int i = 0; i < keys.length; i++) { Object o = map.remove(keys[i]); assertTrue("First map.remove should return null", o == null); } verify(); resetFull(); for (int i = 0; i < keys.length; i++) { Object o = map.remove(keys[i]); confirmed.remove(keys[i]); verify(); assertEquals("map.remove with valid key should return value", values[i], o); } Object[] other = getOtherKeys(); resetFull(); int size = map.size(); for (int i = 0; i < other.length; i++) { Object o = map.remove(other[i]); assertEquals("map.remove for nonexistent key should return null", o, null); assertEquals("map.remove for nonexistent key should not " + "shrink map", size, map.size()); } verify(); } //----------------------------------------------------------------------- /** * Tests that the {@link java.util.Map#values} collection is backed by * the underlying map for clear(). */ public void testValuesClearChangesMap() { if (!isRemoveSupported()) return; // clear values, reflected in map resetFull(); Collection values = map.values(); assertTrue(map.size() > 0); assertTrue(values.size() > 0); values.clear(); assertTrue(map.size() == 0); assertTrue(values.size() == 0); // clear map, reflected in values resetFull(); values = map.values(); assertTrue(map.size() > 0); assertTrue(values.size() > 0); map.clear(); assertTrue(map.size() == 0); assertTrue(values.size() == 0); } /** * Tests that the {@link java.util.Map#keySet} collection is backed by * the underlying map for clear(). */ public void testKeySetClearChangesMap() { if (!isRemoveSupported()) return; // clear values, reflected in map resetFull(); Set keySet = map.keySet(); assertTrue(map.size() > 0); assertTrue(keySet.size() > 0); keySet.clear(); assertTrue(map.size() == 0); assertTrue(keySet.size() == 0); // clear map, reflected in values resetFull(); keySet = map.keySet(); assertTrue(map.size() > 0); assertTrue(keySet.size() > 0); map.clear(); assertTrue(map.size() == 0); assertTrue(keySet.size() == 0); } /** * Tests that the {@link java.util.Map#entrySet()} collection is backed by * the underlying map for clear(). */ public void testEntrySetClearChangesMap() { if (!isRemoveSupported()) return; // clear values, reflected in map resetFull(); Set entrySet = map.entrySet(); assertTrue(map.size() > 0); assertTrue(entrySet.size() > 0); entrySet.clear(); assertTrue(map.size() == 0); assertTrue(entrySet.size() == 0); // clear map, reflected in values resetFull(); entrySet = map.entrySet(); assertTrue(map.size() > 0); assertTrue(entrySet.size() > 0); map.clear(); assertTrue(map.size() == 0); assertTrue(entrySet.size() == 0); } //----------------------------------------------------------------------- public void testEntrySetContains1() { resetFull(); Set entrySet = map.entrySet(); Map.Entry entry = (Map.Entry) entrySet.iterator().next(); assertEquals(true, entrySet.contains(entry)); } public void testEntrySetContains2() { resetFull(); Set entrySet = map.entrySet(); Map.Entry entry = (Map.Entry) entrySet.iterator().next(); Map.Entry test = cloneMapEntry(entry); assertEquals(true, entrySet.contains(test)); } public void testEntrySetContains3() { resetFull(); Set entrySet = map.entrySet(); Map.Entry entry = (Map.Entry) entrySet.iterator().next(); HashMap temp = new HashMap(); temp.put(entry.getKey(), "A VERY DIFFERENT VALUE"); Map.Entry test = (Map.Entry) temp.entrySet().iterator().next(); assertEquals(false, entrySet.contains(test)); } public void testEntrySetRemove1() { if (!isRemoveSupported()) return; resetFull(); int size = map.size(); Set entrySet = map.entrySet(); Map.Entry entry = (Map.Entry) entrySet.iterator().next(); Object key = entry.getKey(); assertEquals(true, entrySet.remove(entry)); assertEquals(false, map.containsKey(key)); assertEquals(size - 1, map.size()); } public void testEntrySetRemove2() { if (!isRemoveSupported()) return; resetFull(); int size = map.size(); Set entrySet = map.entrySet(); Map.Entry entry = (Map.Entry) entrySet.iterator().next(); Object key = entry.getKey(); Map.Entry test = cloneMapEntry(entry); assertEquals(true, entrySet.remove(test)); assertEquals(false, map.containsKey(key)); assertEquals(size - 1, map.size()); } public void testEntrySetRemove3() { if (!isRemoveSupported()) return; resetFull(); int size = map.size(); Set entrySet = map.entrySet(); Map.Entry entry = (Map.Entry) entrySet.iterator().next(); Object key = entry.getKey(); HashMap temp = new HashMap(); temp.put(entry.getKey(), "A VERY DIFFERENT VALUE"); Map.Entry test = (Map.Entry) temp.entrySet().iterator().next(); assertEquals(false, entrySet.remove(test)); assertEquals(true, map.containsKey(key)); assertEquals(size, map.size()); } //----------------------------------------------------------------------- /** * Tests that the {@link java.util.Map#values} collection is backed by * the underlying map by removing from the values collection * and testing if the value was removed from the map. *

                  * We should really test the "vice versa" case--that values removed * from the map are removed from the values collection--also, * but that's a more difficult test to construct (lacking a * "removeValue" method.) *

                  *

                  * See bug * 9573. *

                  */ public void testValuesRemoveChangesMap() { resetFull(); Object[] sampleValues = getSampleValues(); Collection values = map.values(); for (int i = 0; i < sampleValues.length; i++) { if (map.containsValue(sampleValues[i])) { int j = 0; // loop counter prevents infinite loops when remove is broken while (values.contains(sampleValues[i]) && j < 10000) { try { values.remove(sampleValues[i]); } catch (UnsupportedOperationException e) { // if values.remove is unsupported, just skip this test return; } j++; } assertTrue("values().remove(obj) is broken", j < 10000); assertTrue("Value should have been removed from the underlying map.", !map.containsValue(sampleValues[i])); } } } /** * Tests that the {@link java.util.Map#keySet} set is backed by * the underlying map by removing from the keySet set * and testing if the key was removed from the map. */ public void testKeySetRemoveChangesMap() { resetFull(); Object[] sampleKeys = getSampleKeys(); Set keys = map.keySet(); for (int i = 0; i < sampleKeys.length; i++) { try { keys.remove(sampleKeys[i]); } catch (UnsupportedOperationException e) { // if key.remove is unsupported, just skip this test return; } assertTrue("Key should have been removed from the underlying map.", !map.containsKey(sampleKeys[i])); } } // TODO: Need: // testValuesRemovedFromEntrySetAreRemovedFromMap // same for EntrySet/KeySet/values's // Iterator.remove, removeAll, retainAll /** * Utility methods to create an array of Map.Entry objects * out of the given key and value arrays.

                  * * @param keys the array of keys * @param values the array of values * @return an array of Map.Entry of those keys to those values */ private Map.Entry[] makeEntryArray(Object[] keys, Object[] values) { Map.Entry[] result = new Map.Entry[keys.length]; for (int i = 0; i < keys.length; i++) { MultiMap map = makeConfirmedMap(); map.put(keys[i], values[i]); result[i] = (Map.Entry) map.entrySet().iterator().next(); } return result; } /** * Bulk test {@link java.util.Map#entrySet()}. This method runs through all of * the tests in {@link org.apache.commons.collections15.set.AbstractTestSet}. * After modification operations, {@link #verify()} is invoked to ensure * that the map and the other collection views are still valid. * * @return a {@link org.apache.commons.collections15.set.AbstractTestSet} instance for testing the map's entry set */ public BulkTest bulkTestMapEntrySet() { return new TestMapEntrySet(); } public class TestMapEntrySet extends AbstractTestSet { public TestMapEntrySet() { super("MapEntrySet"); } // Have to implement manually; entrySet doesn't support addAll public Object[] getFullElements() { Object[] k = getSampleKeys(); Object[] v = getSampleValues(); return makeEntryArray(k, v); } // Have to implement manually; entrySet doesn't support addAll public Object[] getOtherElements() { Object[] k = getOtherKeys(); Object[] v = getOtherValues(); return makeEntryArray(k, v); } public Set makeEmptySet() { return makeEmptyMap().entrySet(); } public Set makeFullSet() { return makeFullMap().entrySet(); } public boolean isAddSupported() { // Collection views don't support add operations. return false; } public boolean isRemoveSupported() { // Entry set should only support remove if map does return AbstractTestMultiMap.this.isRemoveSupported(); } public boolean isGetStructuralModify() { return AbstractTestMultiMap.this.isGetStructuralModify(); } public boolean isTestSerialization() { return false; } public void resetFull() { AbstractTestMultiMap.this.resetFull(); collection = map.entrySet(); TestMapEntrySet.this.confirmed = AbstractTestMultiMap.this.confirmed.entrySet(); } public void resetEmpty() { AbstractTestMultiMap.this.resetEmpty(); collection = map.entrySet(); TestMapEntrySet.this.confirmed = AbstractTestMultiMap.this.confirmed.entrySet(); } public void testMapEntrySetIteratorEntry() { resetFull(); Iterator it = collection.iterator(); int count = 0; while (it.hasNext()) { Map.Entry entry = (Map.Entry) it.next(); assertEquals(true, AbstractTestMultiMap.this.map.containsKey(entry.getKey())); assertEquals(true, AbstractTestMultiMap.this.map.containsValue(entry.getValue())); if (isGetStructuralModify() == false) { assertEquals(AbstractTestMultiMap.this.map.get(entry.getKey()), entry.getValue()); } count++; } assertEquals(collection.size(), count); } public void testMapEntrySetIteratorEntrySetValue() { Object key1 = getSampleKeys()[0]; Object key2 = (getSampleKeys().length == 1 ? getSampleKeys()[0] : getSampleKeys()[1]); Object newValue1 = getNewSampleValues()[0]; Object newValue2 = (getNewSampleValues().length == 1 ? getNewSampleValues()[0] : getNewSampleValues()[1]); resetFull(); // explicitly get entries as sample values/keys are connected for some maps // such as BeanMap Iterator it = TestMapEntrySet.this.collection.iterator(); Map.Entry entry1 = getEntry(it, key1); it = TestMapEntrySet.this.collection.iterator(); Map.Entry entry2 = getEntry(it, key2); Iterator itConfirmed = TestMapEntrySet.this.confirmed.iterator(); Map.Entry entryConfirmed1 = getEntry(itConfirmed, key1); itConfirmed = TestMapEntrySet.this.confirmed.iterator(); Map.Entry entryConfirmed2 = getEntry(itConfirmed, key2); verify(); if (isSetValueSupported() == false) { try { entry1.setValue(newValue1); } catch (UnsupportedOperationException ex) { } return; } entry1.setValue(newValue1); entryConfirmed1.setValue(newValue1); assertEquals(newValue1, entry1.getValue()); assertEquals(true, AbstractTestMultiMap.this.map.containsKey(entry1.getKey())); assertEquals(true, AbstractTestMultiMap.this.map.containsValue(newValue1)); assertEquals(newValue1, AbstractTestMultiMap.this.map.get(entry1.getKey())); verify(); entry1.setValue(newValue1); entryConfirmed1.setValue(newValue1); assertEquals(newValue1, entry1.getValue()); assertEquals(true, AbstractTestMultiMap.this.map.containsKey(entry1.getKey())); assertEquals(true, AbstractTestMultiMap.this.map.containsValue(newValue1)); assertEquals(newValue1, AbstractTestMultiMap.this.map.get(entry1.getKey())); verify(); entry2.setValue(newValue2); entryConfirmed2.setValue(newValue2); assertEquals(newValue2, entry2.getValue()); assertEquals(true, AbstractTestMultiMap.this.map.containsKey(entry2.getKey())); assertEquals(true, AbstractTestMultiMap.this.map.containsValue(newValue2)); assertEquals(newValue2, AbstractTestMultiMap.this.map.get(entry2.getKey())); verify(); } public Map.Entry getEntry(Iterator itConfirmed, Object key) { Map.Entry entry = null; while (itConfirmed.hasNext()) { Map.Entry temp = (Map.Entry) itConfirmed.next(); if (temp.getKey() == null) { if (key == null) { entry = temp; break; } } else if (temp.getKey().equals(key)) { entry = temp; break; } } assertNotNull("No matching entry in map for key '" + key + "'", entry); return entry; } public void testMapEntrySetRemoveNonMapEntry() { if (isRemoveSupported() == false) return; resetFull(); assertEquals(false, getSet().remove(null)); assertEquals(false, getSet().remove(new Object())); } public void verify() { super.verify(); AbstractTestMultiMap.this.verify(); } } /** * Bulk test {@link java.util.Map#keySet()}. This method runs through all of * the tests in {@link org.apache.commons.collections15.set.AbstractTestSet}. * After modification operations, {@link #verify()} is invoked to ensure * that the map and the other collection views are still valid. * * @return a {@link org.apache.commons.collections15.set.AbstractTestSet} instance for testing the map's key set */ public BulkTest bulkTestMapKeySet() { return new TestMapKeySet(); } public class TestMapKeySet extends AbstractTestSet { public TestMapKeySet() { super(""); } public Object[] getFullElements() { return getSampleKeys(); } public Object[] getOtherElements() { return getOtherKeys(); } public Set makeEmptySet() { return makeEmptyMap().keySet(); } public Set makeFullSet() { return makeFullMap().keySet(); } public boolean isNullSupported() { return AbstractTestMultiMap.this.isAllowNullKey(); } public boolean isAddSupported() { return false; } public boolean isRemoveSupported() { return AbstractTestMultiMap.this.isRemoveSupported(); } public boolean isTestSerialization() { return false; } public void resetEmpty() { AbstractTestMultiMap.this.resetEmpty(); collection = map.keySet(); TestMapKeySet.this.confirmed = AbstractTestMultiMap.this.confirmed.keySet(); } public void resetFull() { AbstractTestMultiMap.this.resetFull(); collection = map.keySet(); TestMapKeySet.this.confirmed = AbstractTestMultiMap.this.confirmed.keySet(); } public void verify() { super.verify(); AbstractTestMultiMap.this.verify(); } } /** * Bulk test {@link java.util.Map#values()}. This method runs through all of * the tests in {@link org.apache.commons.collections15.collection.AbstractTestCollection}. * After modification operations, {@link #verify()} is invoked to ensure * that the map and the other collection views are still valid. * * @return a {@link org.apache.commons.collections15.collection.AbstractTestCollection} instance for testing the map's * values collection */ public BulkTest bulkTestMapValues() { return new TestMapValues(); } public class TestMapValues extends AbstractTestCollection { public TestMapValues() { super(""); } public Object[] getFullElements() { return getSampleValues(); } public Object[] getOtherElements() { return getOtherValues(); } public Collection makeCollection() { return makeEmptyMap().values(); } public Collection makeFullCollection() { return makeFullMap().values(); } public boolean isNullSupported() { return AbstractTestMultiMap.this.isAllowNullKey(); } public boolean isAddSupported() { return false; } public boolean isRemoveSupported() { return AbstractTestMultiMap.this.isRemoveSupported(); } public boolean isTestSerialization() { return false; } public boolean areEqualElementsDistinguishable() { // equal values are associated with different keys, so they are // distinguishable. return true; } public Collection makeConfirmedCollection() { // never gets called, reset methods are overridden return null; } public Collection makeConfirmedFullCollection() { // never gets called, reset methods are overridden return null; } public void resetFull() { AbstractTestMultiMap.this.resetFull(); collection = map.values(); TestMapValues.this.confirmed = AbstractTestMultiMap.this.confirmed.values(); } public void resetEmpty() { AbstractTestMultiMap.this.resetEmpty(); collection = map.values(); TestMapValues.this.confirmed = AbstractTestMultiMap.this.confirmed.values(); } public void verify() { super.verify(); AbstractTestMultiMap.this.verify(); } // TODO: should test that a remove on the values collection view // removes the proper mapping and not just any mapping that may have // the value equal to the value returned from the values iterator. } /** * Resets the {@link #map}, {@link #entrySet}, {@link #keySet}, * {@link #values} and {@link #confirmed} fields to empty. */ public void resetEmpty() { this.map = makeEmptyMap(); views(); this.confirmed = makeConfirmedMap(); } /** * Resets the {@link #map}, {@link #entrySet}, {@link #keySet}, * {@link #values} and {@link #confirmed} fields to full. */ public void resetFull() { this.map = makeFullMap(); views(); this.confirmed = makeConfirmedMap(); Object[] k = getSampleKeys(); Object[] v = getSampleValues(); for (int i = 0; i < k.length; i++) { confirmed.put(k[i], v[i]); } } /** * Resets the collection view fields. */ private void views() { this.keySet = map.keySet(); this.values = map.values(); this.entrySet = map.entrySet(); } /** * Verifies that {@link #map} is still equal to {@link #confirmed}. * This method checks that the map is equal to the HashMap, * and that the map's collection views are still equal to * the HashMap's collection views. An equals test * is done on the maps and their collection views; their size and * isEmpty results are compared; their hashCodes are * compared; and containsAll tests are run on the * collection views. */ public void verify() { verifyMap(); verifyEntrySet(); verifyKeySet(); verifyValues(); } public void verifyMap() { int size = confirmed.size(); boolean empty = confirmed.isEmpty(); assertEquals("Map should be same size as HashMap", size, map.size()); assertEquals("Map should be empty if HashMap is", empty, map.isEmpty()); assertEquals("hashCodes should be the same", confirmed.hashCode(), map.hashCode()); // this fails for LRUMap because confirmed.equals() somehow modifies // map, causing concurrent modification exceptions. //assertEquals("Map should still equal HashMap", confirmed, map); // this works though and performs the same verification: assertTrue("Map should still equal HashMap", map.equals(confirmed)); // TODO: this should really be reexamined to figure out why LRU map // behaves like it does (the equals shouldn't modify since all accesses // by the confirmed collection should be through an iterator, thus not // causing LRUMap to change). } public void verifyEntrySet() { int size = confirmed.size(); boolean empty = confirmed.isEmpty(); assertEquals("entrySet should be same size as HashMap's" + "\nTest: " + entrySet + "\nReal: " + confirmed.entrySet(), size, entrySet.size()); assertEquals("entrySet should be empty if HashMap is" + "\nTest: " + entrySet + "\nReal: " + confirmed.entrySet(), empty, entrySet.isEmpty()); assertTrue("entrySet should contain all HashMap's elements" + "\nTest: " + entrySet + "\nReal: " + confirmed.entrySet(), entrySet.containsAll(confirmed.entrySet())); assertEquals("entrySet hashCodes should be the same" + "\nTest: " + entrySet + "\nReal: " + confirmed.entrySet(), confirmed.entrySet().hashCode(), entrySet.hashCode()); assertEquals("Map's entry set should still equal HashMap's", confirmed.entrySet(), entrySet); } public void verifyKeySet() { int size = confirmed.size(); boolean empty = confirmed.isEmpty(); assertEquals("keySet should be same size as HashMap's" + "\nTest: " + keySet + "\nReal: " + confirmed.keySet(), size, keySet.size()); assertEquals("keySet should be empty if HashMap is" + "\nTest: " + keySet + "\nReal: " + confirmed.keySet(), empty, keySet.isEmpty()); assertTrue("keySet should contain all HashMap's elements" + "\nTest: " + keySet + "\nReal: " + confirmed.keySet(), keySet.containsAll(confirmed.keySet())); assertEquals("keySet hashCodes should be the same" + "\nTest: " + keySet + "\nReal: " + confirmed.keySet(), confirmed.keySet().hashCode(), keySet.hashCode()); assertEquals("Map's key set should still equal HashMap's", confirmed.keySet(), keySet); } public void verifyValues() { List known = new ArrayList(confirmed.values()); List test = new ArrayList(values); int size = confirmed.size(); boolean empty = confirmed.isEmpty(); assertEquals("values should be same size as HashMap's" + "\nTest: " + test + "\nReal: " + known, size, values.size()); assertEquals("values should be empty if HashMap is" + "\nTest: " + test + "\nReal: " + known, empty, values.isEmpty()); assertTrue("values should contain all HashMap's elements" + "\nTest: " + test + "\nReal: " + known, test.containsAll(known)); assertTrue("values should contain all HashMap's elements" + "\nTest: " + test + "\nReal: " + known, known.containsAll(test)); // originally coded to use a HashBag, but now separate jar so... for (Iterator it = known.iterator(); it.hasNext();) { boolean removed = test.remove(it.next()); assertTrue("Map's values should still equal HashMap's", removed); } assertTrue("Map's values should still equal HashMap's", test.isEmpty()); } /** * Erases any leftover instance variables by setting them to null. */ public void tearDown() throws Exception { map = null; keySet = null; entrySet = null; values = null; confirmed = null; } } collections-generic-4.01/src/test/org/apache/commons/collections15/TestTypedCollection.java0000644000175000017500000000445610464140761032331 0ustar giovannigiovanni/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15; import java.util.ArrayList; import java.util.Collection; import java.util.List; /** * Tests TypedCollection. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:39 $ */ public abstract class TestTypedCollection extends BulkTest { public TestTypedCollection(String name) { super(name); } protected abstract Collection typedCollection(); protected Class getType() { return String.class; } public void testIllegalAdd() { Collection c = typedCollection(); Integer i = new Integer(3); try { c.add(i); fail("Integer should fail string predicate."); } catch (IllegalArgumentException e) { // expected } assertTrue("Collection shouldn't contain illegal element", !c.contains(i)); } public void testIllegalAddAll() { Collection c = typedCollection(); List elements = new ArrayList(); elements.add("one"); elements.add("two"); elements.add(new Integer(3)); elements.add("four"); try { c.addAll(elements); fail("Integer should fail string predicate."); } catch (IllegalArgumentException e) { // expected } assertTrue("Collection shouldn't contain illegal element", !c.contains("one")); assertTrue("Collection shouldn't contain illegal element", !c.contains("two")); assertTrue("Collection shouldn't contain illegal element", !c.contains(new Integer(3))); assertTrue("Collection shouldn't contain illegal element", !c.contains("four")); } } collections-generic-4.01/src/test/org/apache/commons/collections15/TestMapUtils.java0000644000175000017500000005356210464140765030774 0ustar giovannigiovanni/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15; import junit.framework.Test; import org.apache.commons.collections15.map.PredicatedMap; import org.apache.commons.collections15.map.TestPredicatedMap; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.util.*; /** * Tests for MapUtils. * * @author Stephen Colebourne * @author Arun Mammen Thomas * @author Max Rydahl Andersen * @author Matt Hall, John Watkinson, Janek Bogucki * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:39 $ */ public class TestMapUtils extends BulkTest { public TestMapUtils(String name) { super(name); } public static Test suite() { return BulkTest.makeSuite(TestMapUtils.class); } public Predicate getPredicate() { return new Predicate() { public boolean evaluate(Object o) { return o instanceof String; } }; } public void testPredicatedMap() { Predicate p = getPredicate(); Map map = MapUtils.predicatedMap(new HashMap(), p, p); assertTrue("returned object should be a PredicatedMap", map instanceof PredicatedMap); try { map = MapUtils.predicatedMap(null, p, p); fail("Expecting IllegalArgumentException for null map."); } catch (IllegalArgumentException e) { // expected } } // Since a typed map is a predicated map, I copied the tests for predicated map public void testTypedMapIllegalPut() { final Map map = MapUtils.typedMap(new HashMap(), String.class, String.class); try { map.put("Hi", new Integer(3)); fail("Illegal value should raise IllegalArgument"); } catch (IllegalArgumentException e) { // expected } try { map.put(new Integer(3), "Hi"); fail("Illegal key should raise IllegalArgument"); } catch (IllegalArgumentException e) { // expected } assertTrue(!map.containsKey(new Integer(3))); assertTrue(!map.containsValue(new Integer(3))); Map map2 = new HashMap(); map2.put("A", "a"); map2.put("B", "b"); map2.put("C", "c"); map2.put("c", new Integer(3)); try { map.putAll(map2); fail("Illegal value should raise IllegalArgument"); } catch (IllegalArgumentException e) { // expected } map.put("E", "e"); Iterator iterator = map.entrySet().iterator(); try { Map.Entry entry = (Map.Entry) iterator.next(); entry.setValue(new Integer(3)); fail("Illegal value should raise IllegalArgument"); } catch (IllegalArgumentException e) { // expected } } public BulkTest bulkTestTypedMap() { return new TestPredicatedMap("") { public boolean isAllowNullKey() { return false; } public boolean isAllowNullValue() { return false; } public Map makeEmptyMap() { return MapUtils.typedMap(new HashMap(), String.class, String.class); } }; } /* public void testLazyMapFactory() { Factory factory = FactoryUtils.constantFactory(new Integer(5)); Map map = MapUtils.lazyMap(new HashMap(), factory); assertTrue(map instanceof LazyMap); try { map = MapUtils.lazyMap(new HashMap(), (Factory) null); fail("Expecting IllegalArgumentException for null factory"); } catch (IllegalArgumentException e) { // expected } try { map = MapUtils.lazyMap(null, factory); fail("Expecting IllegalArgumentException for null map"); } catch (IllegalArgumentException e) { // expected } Transformer transformer = TransformerUtils.asTransformer(factory); map = MapUtils.lazyMap(new HashMap(), transformer); assertTrue(map instanceof LazyMap); try { map = MapUtils.lazyMap(new HashMap(), (Transformer) null); fail("Expecting IllegalArgumentException for null transformer"); } catch (IllegalArgumentException e) { // expected } try { map = MapUtils.lazyMap(null, transformer); fail("Expecting IllegalArgumentException for null map"); } catch (IllegalArgumentException e) { // expected } } public void testLazyMapTransformer() { Map map = MapUtils.lazyMap(new HashMap(), new Transformer() { public Object transform(Object mapKey) { if (mapKey instanceof String) { return new Integer((String) mapKey); } return null; } }); assertEquals(0, map.size()); Integer i1 = (Integer) map.get("5"); assertEquals(new Integer(5), i1); assertEquals(1, map.size()); Integer i2 = (Integer) map.get(new String(new char[] {'5'})); assertEquals(new Integer(5), i2); assertEquals(1, map.size()); assertSame(i1, i2); } */ public void testInvertMap() { final Map in = new HashMap(5, 1); in.put("1", "A"); in.put("2", "B"); in.put("3", "C"); in.put("4", "D"); in.put("5", "E"); final Set inKeySet = new HashSet(in.keySet()); final Set inValSet = new HashSet(in.values()); final Map out = MapUtils.invertMap(in); final Set outKeySet = new HashSet(out.keySet()); final Set outValSet = new HashSet(out.values()); assertTrue(inKeySet.equals(outValSet)); assertTrue(inValSet.equals(outKeySet)); assertEquals(out.get("A"), "1"); assertEquals(out.get("B"), "2"); assertEquals(out.get("C"), "3"); assertEquals(out.get("D"), "4"); assertEquals(out.get("E"), "5"); } public void testConvertResourceBundle() { final Map in = new HashMap(5, 1); in.put("1", "A"); in.put("2", "B"); in.put("3", "C"); in.put("4", "D"); in.put("5", "E"); ResourceBundle b = new ListResourceBundle() { public Object[][] getContents() { final Object[][] contents = new Object[in.size()][2]; final Iterator i = in.keySet().iterator(); int n = 0; while (i.hasNext()) { final Object key = i.next(); final Object val = in.get(key); contents[n][0] = key; contents[n][1] = val; ++n; } return contents; } }; final Map out = MapUtils.toMap(b); assertTrue(in.equals(out)); } public void testDebugAndVerbosePrintCasting() { final Map inner = new HashMap(2, 1); inner.put(new Integer(2), "B"); inner.put(new Integer(3), "C"); final Map outer = new HashMap(2, 1); outer.put(new Integer(0), inner); outer.put(new Integer(1), "A"); final ByteArrayOutputStream out = new ByteArrayOutputStream(); final PrintStream outPrint = new PrintStream(out); try { MapUtils.debugPrint(outPrint, "Print Map", outer); } catch (final ClassCastException e) { fail("No Casting should be occurring!"); } } public void testDebugAndVerbosePrintNullMap() { final ByteArrayOutputStream out = new ByteArrayOutputStream(); final PrintStream outPrint = new PrintStream(out); final String LABEL = "Print Map"; outPrint.println(LABEL + " = " + String.valueOf((Object) null)); final String EXPECTED_OUT = out.toString(); out.reset(); MapUtils.debugPrint(outPrint, LABEL, null); assertEquals(EXPECTED_OUT, out.toString()); out.reset(); MapUtils.verbosePrint(outPrint, LABEL, null); assertEquals(EXPECTED_OUT, out.toString()); } public void testVerbosePrintNullLabel() { final ByteArrayOutputStream out = new ByteArrayOutputStream(); final PrintStream outPrint = new PrintStream(out); final String INDENT = " "; final Map map = new TreeMap(); // treeMap guarantees order across JDKs for test map.put(new Integer(2), "B"); map.put(new Integer(3), "C"); map.put(new Integer(4), null); outPrint.println("{"); outPrint.println(INDENT + "2 = B"); outPrint.println(INDENT + "3 = C"); outPrint.println(INDENT + "4 = null"); outPrint.println("}"); final String EXPECTED_OUT = out.toString(); out.reset(); MapUtils.verbosePrint(outPrint, null, map); assertEquals(EXPECTED_OUT, out.toString()); } public void testDebugPrintNullLabel() { final ByteArrayOutputStream out = new ByteArrayOutputStream(); final PrintStream outPrint = new PrintStream(out); final String INDENT = " "; final Map map = new TreeMap(); // treeMap guarantees order across JDKs for test map.put(new Integer(2), "B"); map.put(new Integer(3), "C"); map.put(new Integer(4), null); outPrint.println("{"); outPrint.println(INDENT + "2 = B " + String.class.getName()); outPrint.println(INDENT + "3 = C " + String.class.getName()); outPrint.println(INDENT + "4 = null"); outPrint.println("} " + TreeMap.class.getName()); final String EXPECTED_OUT = out.toString(); out.reset(); MapUtils.debugPrint(outPrint, null, map); assertEquals(EXPECTED_OUT, out.toString()); } public void testVerbosePrintNullLabelAndMap() { final ByteArrayOutputStream out = new ByteArrayOutputStream(); final PrintStream outPrint = new PrintStream(out); outPrint.println("null"); final String EXPECTED_OUT = out.toString(); out.reset(); MapUtils.verbosePrint(outPrint, null, null); assertEquals(EXPECTED_OUT, out.toString()); } public void testDebugPrintNullLabelAndMap() { final ByteArrayOutputStream out = new ByteArrayOutputStream(); final PrintStream outPrint = new PrintStream(out); outPrint.println("null"); final String EXPECTED_OUT = out.toString(); out.reset(); MapUtils.debugPrint(outPrint, null, null); assertEquals(EXPECTED_OUT, out.toString()); } public void testVerbosePrintNullStream() { try { MapUtils.verbosePrint(null, "Map", new HashMap()); fail("Should generate NullPointerException"); } catch (NullPointerException expected) { } } public void testDebugPrintNullStream() { try { MapUtils.debugPrint(null, "Map", new HashMap()); fail("Should generate NullPointerException"); } catch (NullPointerException expected) { } } public void testDebugPrintNullKey() { final ByteArrayOutputStream out = new ByteArrayOutputStream(); final PrintStream outPrint = new PrintStream(out); final String INDENT = " "; final Map map = new HashMap(); map.put(null, "A"); outPrint.println("{"); outPrint.println(INDENT + "null = A " + String.class.getName()); outPrint.println("} " + HashMap.class.getName()); final String EXPECTED_OUT = out.toString(); out.reset(); MapUtils.debugPrint(outPrint, null, map); assertEquals(EXPECTED_OUT, out.toString()); } public void testVerbosePrintNullKey() { final ByteArrayOutputStream out = new ByteArrayOutputStream(); final PrintStream outPrint = new PrintStream(out); final String INDENT = " "; final Map map = new HashMap(); map.put(null, "A"); outPrint.println("{"); outPrint.println(INDENT + "null = A"); outPrint.println("}"); final String EXPECTED_OUT = out.toString(); out.reset(); MapUtils.verbosePrint(outPrint, null, map); assertEquals(EXPECTED_OUT, out.toString()); } public void testDebugPrintNullKeyToMap1() { final ByteArrayOutputStream out = new ByteArrayOutputStream(); final PrintStream outPrint = new PrintStream(out); final String INDENT = " "; final Map map = new HashMap(); map.put(null, map); outPrint.println("{"); outPrint.println(INDENT + "null = (this Map) " + HashMap.class.getName()); outPrint.println("} " + HashMap.class.getName()); final String EXPECTED_OUT = out.toString(); out.reset(); MapUtils.debugPrint(outPrint, null, map); assertEquals(EXPECTED_OUT, out.toString()); } public void testVerbosePrintNullKeyToMap1() { final ByteArrayOutputStream out = new ByteArrayOutputStream(); final PrintStream outPrint = new PrintStream(out); final String INDENT = " "; final Map map = new HashMap(); map.put(null, map); outPrint.println("{"); outPrint.println(INDENT + "null = (this Map)"); outPrint.println("}"); final String EXPECTED_OUT = out.toString(); out.reset(); MapUtils.verbosePrint(outPrint, null, map); assertEquals(EXPECTED_OUT, out.toString()); } public void testDebugPrintNullKeyToMap2() { final ByteArrayOutputStream out = new ByteArrayOutputStream(); final PrintStream outPrint = new PrintStream(out); final String INDENT = " "; final Map map = new HashMap(); final Map map2 = new HashMap(); map.put(null, map2); map2.put("2", "B"); outPrint.println("{"); outPrint.println(INDENT + "null = "); outPrint.println(INDENT + "{"); outPrint.println(INDENT + INDENT + "2 = B " + String.class.getName()); outPrint.println(INDENT + "} " + HashMap.class.getName()); outPrint.println("} " + HashMap.class.getName()); final String EXPECTED_OUT = out.toString(); out.reset(); MapUtils.debugPrint(outPrint, null, map); assertEquals(EXPECTED_OUT, out.toString()); } public void testVerbosePrintNullKeyToMap2() { final ByteArrayOutputStream out = new ByteArrayOutputStream(); final PrintStream outPrint = new PrintStream(out); final String INDENT = " "; final Map map = new HashMap(); final Map map2 = new HashMap(); map.put(null, map2); map2.put("2", "B"); outPrint.println("{"); outPrint.println(INDENT + "null = "); outPrint.println(INDENT + "{"); outPrint.println(INDENT + INDENT + "2 = B"); outPrint.println(INDENT + "}"); outPrint.println("}"); final String EXPECTED_OUT = out.toString(); out.reset(); MapUtils.verbosePrint(outPrint, null, map); assertEquals(EXPECTED_OUT, out.toString()); } public void testVerbosePrint() { final ByteArrayOutputStream out = new ByteArrayOutputStream(); final PrintStream outPrint = new PrintStream(out); final String LABEL = "Print Map"; final String INDENT = " "; outPrint.println(LABEL + " = "); outPrint.println("{"); outPrint.println(INDENT + "0 = A"); outPrint.println(INDENT + "1 = "); outPrint.println(INDENT + "{"); outPrint.println(INDENT + INDENT + "2 = B"); outPrint.println(INDENT + INDENT + "3 = C"); outPrint.println(INDENT + "}"); outPrint.println(INDENT + "7 = (this Map)"); outPrint.println("}"); final String EXPECTED_OUT = out.toString(); out.reset(); final Map inner = new TreeMap(); // treeMap guarantees order across JDKs for test inner.put(new Integer(2), "B"); inner.put(new Integer(3), "C"); final Map outer = new TreeMap(); outer.put(new Integer(1), inner); outer.put(new Integer(0), "A"); outer.put(new Integer(7), outer); MapUtils.verbosePrint(outPrint, "Print Map", outer); assertEquals(EXPECTED_OUT, out.toString()); } public void testDebugPrint() { final ByteArrayOutputStream out = new ByteArrayOutputStream(); final PrintStream outPrint = new PrintStream(out); final String LABEL = "Print Map"; final String INDENT = " "; outPrint.println(LABEL + " = "); outPrint.println("{"); outPrint.println(INDENT + "0 = A " + String.class.getName()); outPrint.println(INDENT + "1 = "); outPrint.println(INDENT + "{"); outPrint.println(INDENT + INDENT + "2 = B " + String.class.getName()); outPrint.println(INDENT + INDENT + "3 = C " + String.class.getName()); outPrint.println(INDENT + "} " + TreeMap.class.getName()); outPrint.println(INDENT + "7 = (this Map) " + TreeMap.class.getName()); outPrint.println("} " + TreeMap.class.getName()); final String EXPECTED_OUT = out.toString(); out.reset(); final Map inner = new TreeMap(); // treeMap guarantees order across JDKs for test inner.put(new Integer(2), "B"); inner.put(new Integer(3), "C"); final Map outer = new TreeMap(); outer.put(new Integer(1), inner); outer.put(new Integer(0), "A"); outer.put(new Integer(7), outer); MapUtils.debugPrint(outPrint, "Print Map", outer); assertEquals(EXPECTED_OUT, out.toString()); } public void testVerbosePrintSelfReference() { final ByteArrayOutputStream out = new ByteArrayOutputStream(); final PrintStream outPrint = new PrintStream(out); final String LABEL = "Print Map"; final String INDENT = " "; final Map grandfather = new TreeMap();// treeMap guarantees order across JDKs for test final Map father = new TreeMap(); final Map son = new TreeMap(); grandfather.put(new Integer(0), "A"); grandfather.put(new Integer(1), father); father.put(new Integer(2), "B"); father.put(new Integer(3), grandfather); father.put(new Integer(4), son); son.put(new Integer(5), "C"); son.put(new Integer(6), grandfather); son.put(new Integer(7), father); outPrint.println(LABEL + " = "); outPrint.println("{"); outPrint.println(INDENT + "0 = A"); outPrint.println(INDENT + "1 = "); outPrint.println(INDENT + "{"); outPrint.println(INDENT + INDENT + "2 = B"); outPrint.println(INDENT + INDENT + "3 = (ancestor[0] Map)"); outPrint.println(INDENT + INDENT + "4 = "); outPrint.println(INDENT + INDENT + "{"); outPrint.println(INDENT + INDENT + INDENT + "5 = C"); outPrint.println(INDENT + INDENT + INDENT + "6 = (ancestor[1] Map)"); outPrint.println(INDENT + INDENT + INDENT + "7 = (ancestor[0] Map)"); outPrint.println(INDENT + INDENT + "}"); outPrint.println(INDENT + "}"); outPrint.println("}"); final String EXPECTED_OUT = out.toString(); out.reset(); MapUtils.verbosePrint(outPrint, "Print Map", grandfather); assertEquals(EXPECTED_OUT, out.toString()); } public void testDebugPrintSelfReference() { final ByteArrayOutputStream out = new ByteArrayOutputStream(); final PrintStream outPrint = new PrintStream(out); final String LABEL = "Print Map"; final String INDENT = " "; final Map grandfather = new TreeMap();// treeMap guarantees order across JDKs for test final Map father = new TreeMap(); final Map son = new TreeMap(); grandfather.put(new Integer(0), "A"); grandfather.put(new Integer(1), father); father.put(new Integer(2), "B"); father.put(new Integer(3), grandfather); father.put(new Integer(4), son); son.put(new Integer(5), "C"); son.put(new Integer(6), grandfather); son.put(new Integer(7), father); outPrint.println(LABEL + " = "); outPrint.println("{"); outPrint.println(INDENT + "0 = A " + String.class.getName()); outPrint.println(INDENT + "1 = "); outPrint.println(INDENT + "{"); outPrint.println(INDENT + INDENT + "2 = B " + String.class.getName()); outPrint.println(INDENT + INDENT + "3 = (ancestor[0] Map) " + TreeMap.class.getName()); outPrint.println(INDENT + INDENT + "4 = "); outPrint.println(INDENT + INDENT + "{"); outPrint.println(INDENT + INDENT + INDENT + "5 = C " + String.class.getName()); outPrint.println(INDENT + INDENT + INDENT + "6 = (ancestor[1] Map) " + TreeMap.class.getName()); outPrint.println(INDENT + INDENT + INDENT + "7 = (ancestor[0] Map) " + TreeMap.class.getName()); outPrint.println(INDENT + INDENT + "} " + TreeMap.class.getName()); outPrint.println(INDENT + "} " + TreeMap.class.getName()); outPrint.println("} " + TreeMap.class.getName()); final String EXPECTED_OUT = out.toString(); out.reset(); MapUtils.debugPrint(outPrint, "Print Map", grandfather); assertEquals(EXPECTED_OUT, out.toString()); } } collections-generic-4.01/src/test/org/apache/commons/collections15/collection/0000755000175000017500000000000011664401370027646 5ustar giovannigiovanni././@LongLink0000000000000000000000000000015600000000000011567 Lustar rootrootcollections-generic-4.01/src/test/org/apache/commons/collections15/collection/TestSynchronizedCollection.javacollections-generic-4.01/src/test/org/apache/commons/collections15/collection/TestSynchronizedCollec0000644000175000017500000000503510464140754034240 0ustar giovannigiovanni/* * Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.collection; import junit.framework.Test; import junit.framework.TestSuite; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; /** * Extension of {@link AbstractTestCollection} for exercising the * {@link SynchronizedCollection} implementation. * * @author Phil Steitz * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 19:11:58 $ * @since Commons Collections 3.1 */ public class TestSynchronizedCollection extends AbstractTestCollection { public TestSynchronizedCollection(String testName) { super(testName); } public static Test suite() { return new TestSuite(TestSynchronizedCollection.class); } public static void main(String args[]) { String[] testCaseName = {TestSynchronizedCollection.class.getName()}; junit.textui.TestRunner.main(testCaseName); } //----------------------------------------------------------------------- public Collection makeCollection() { return SynchronizedCollection.decorate(new ArrayList()); } public Collection makeConfirmedCollection() { ArrayList list = new ArrayList(); return list; } public Collection makeConfirmedFullCollection() { ArrayList list = new ArrayList(); list.addAll(Arrays.asList(getFullElements())); return list; } public String getCompatibilityVersion() { return "3.1"; } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk((java.io.Serializable) collection, "D:/dev/collections15/data/test/SynchronizedCollection.emptyCollection.version3.1.obj"); // resetFull(); // writeExternalFormToDisk((java.io.Serializable) collection, "D:/dev/collections15/data/test/SynchronizedCollection.fullCollection.version3.1.obj"); // } } ././@LongLink0000000000000000000000000000015400000000000011565 Lustar rootrootcollections-generic-4.01/src/test/org/apache/commons/collections15/collection/TestPredicatedCollection.javacollections-generic-4.01/src/test/org/apache/commons/collections15/collection/TestPredicatedCollecti0000644000175000017500000001116510464140763034163 0ustar giovannigiovanni/* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.collection; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.collections15.Predicate; import org.apache.commons.collections15.PredicateUtils; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; /** * Extension of {@link TestCollection} for exercising the * {@link PredicatedCollection} implementation. * * @author Matt Hall, John Watkinson, Phil Steitz * @version $Revision: 1.1 $ $Date: 2005/10/11 19:11:58 $ * @since Commons Collections 3.0 */ public class TestPredicatedCollection extends AbstractTestCollection { public TestPredicatedCollection(String name) { super(name); } public static Test suite() { return new TestSuite(TestPredicatedCollection.class); } public static void main(String args[]) { String[] testCaseName = {TestPredicatedCollection.class.getName()}; junit.textui.TestRunner.main(testCaseName); } //------------------------------------------------------------------------ protected Predicate truePredicate = PredicateUtils.truePredicate(); protected Collection decorateCollection(Collection collection, Predicate predicate) { return PredicatedCollection.decorate(collection, predicate); } public Collection makeCollection() { return decorateCollection(new ArrayList(), truePredicate); } public Collection makeConfirmedCollection() { return new ArrayList(); } public Object[] getFullElements() { return new Object[]{"1", "3", "5", "7", "2", "4", "6"}; } public Collection makeFullCollection() { List list = new ArrayList(); list.addAll(Arrays.asList(getFullElements())); return decorateCollection(list, truePredicate); } public Collection makeConfirmedFullCollection() { List list = new ArrayList(); list.addAll(Arrays.asList(getFullElements())); return list; } //----------------------------------------------------------------- protected Predicate testPredicate = new Predicate() { public boolean evaluate(Object o) { return o instanceof String; } }; public Collection makeTestCollection() { return decorateCollection(new ArrayList(), testPredicate); } public void testIllegalAdd() { Collection c = makeTestCollection(); Integer i = new Integer(3); try { c.add(i); fail("Integer should fail string predicate."); } catch (IllegalArgumentException e) { // expected } assertTrue("Collection shouldn't contain illegal element", !c.contains(i)); } public void testIllegalAddAll() { Collection c = makeTestCollection(); List elements = new ArrayList(); elements.add("one"); elements.add("two"); elements.add(new Integer(3)); elements.add("four"); try { c.addAll(elements); fail("Integer should fail string predicate."); } catch (IllegalArgumentException e) { // expected } assertTrue("Collection shouldn't contain illegal element", !c.contains("one")); assertTrue("Collection shouldn't contain illegal element", !c.contains("two")); assertTrue("Collection shouldn't contain illegal element", !c.contains(new Integer(3))); assertTrue("Collection shouldn't contain illegal element", !c.contains("four")); } public String getCompatibilityVersion() { return "3.1"; } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk((java.io.Serializable) collection, "D:/dev/collections15/data/test/PredicatedCollection.emptyCollection.version3.1.obj"); // resetFull(); // writeExternalFormToDisk((java.io.Serializable) collection, "D:/dev/collections15/data/test/PredicatedCollection.fullCollection.version3.1.obj"); // } } ././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootcollections-generic-4.01/src/test/org/apache/commons/collections15/collection/AbstractTestCollection.javacollections-generic-4.01/src/test/org/apache/commons/collections15/collection/AbstractTestCollection0000644000175000017500000013263710464140765034231 0ustar giovannigiovanni/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.collection; import org.apache.commons.collections15.AbstractTestObject; import java.io.*; import java.lang.reflect.Array; import java.util.*; /** * Abstract test class for {@link java.util.Collection} methods and contracts. *

                  * You should create a concrete subclass of this class to test any custom * {@link Collection} implementation. At minimum, you'll have to * implement the {@link #makeCollection()} method. You might want to * override some of the additional public methods as well: *

                  * Element Population Methods *

                  * Override these if your collection restricts what kind of elements are * allowed (for instance, if null is not permitted): *

                    *
                  • {@link #getFullElements()} *
                  • {@link #getOtherElements()} *
                  *

                  * Supported Operation Methods *

                  * Override these if your collection doesn't support certain operations: *

                    *
                  • {@link #isAddSupported()} *
                  • {@link #isRemoveSupported()} *
                  • {@link #areEqualElementsDistinguishable()} *
                  • {@link #isNullSupported()} *
                  • {@link #isFailFastSupported()} *
                  *

                  * Fixture Methods *

                  * Fixtures are used to verify that the the operation results in correct state * for the collection. Basically, the operation is performed against your * collection implementation, and an identical operation is performed against a * confirmed collection implementation. A confirmed collection * implementation is something like java.util.ArrayList, which is * known to conform exactly to its collection interface's contract. After the * operation takes place on both your collection implementation and the * confirmed collection implementation, the two collections15 are compared to see * if their state is identical. The comparison is usually much more involved * than a simple equals test. This verification is used to ensure * proper modifications are made along with ensuring that the collection does * not change when read-only modifications are made. *

                  * The {@link #collection} field holds an instance of your collection * implementation; the {@link #confirmed} field holds an instance of the * confirmed collection implementation. The {@link #resetEmpty()} and * {@link #resetFull()} methods set these fields to empty or full collections15, * so that tests can proceed from a known state. *

                  * After a modification operation to both {@link #collection} and * {@link #confirmed}, the {@link #verify()} method is invoked to compare * the results. You may want to override {@link #verify()} to perform * additional verifications. For instance, when testing the collection * views of a map, {@link AbstractTestMap} would override {@link #verify()} to make * sure the map is changed after the collection view is changed. *

                  * If you're extending this class directly, you will have to provide * implementations for the following: *

                    *
                  • {@link #makeConfirmedCollection()} *
                  • {@link #makeConfirmedFullCollection()} *
                  *

                  * Those methods should provide a confirmed collection implementation * that's compatible with your collection implementation. *

                  * If you're extending {@link AbstractTestList}, {@link AbstractTestSet}, * or {@link AbstractTestBag}, you probably don't have to worry about the * above methods, because those three classes already override the methods * to provide standard JDK confirmed collections15.

                  *

                  * Other notes *

                  * If your {@link Collection} fails one of these tests by design, * you may still use this base set of cases. Simply override the * test case (method) your {@link Collection} fails. * * @author Rodney Waldhoff * @author Paul Jack * @author Michael A. Smith * @author Neil O'Toole * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 19:11:58 $ */ public abstract class AbstractTestCollection extends AbstractTestObject { // // NOTE: // // Collection doesn't define any semantics for equals, and recommends you // use reference-based default behavior of Object.equals. (And a test for // that already exists in AbstractTestObject). Tests for equality of lists, sets // and bags will have to be written in test subclasses. Thus, there is no // tests on Collection.equals nor any for Collection.hashCode. // // These fields are used by reset() and verify(), and any test // method that tests a modification. /** * A collection instance that will be used for testing. */ public Collection collection; /** * Confirmed collection. This is an instance of a collection that is * confirmed to conform exactly to the java.util.Collection contract. * Modification operations are tested by performing a mod on your * collection, performing the exact same mod on an equivalent confirmed * collection, and then calling verify() to make sure your collection * still matches the confirmed collection. */ public Collection confirmed; /** * JUnit constructor. * * @param testName the test class name */ public AbstractTestCollection(String testName) { super(testName); } //----------------------------------------------------------------------- /** * Specifies whether equal elements in the collection are, in fact, * distinguishable with information not readily available. That is, if a * particular value is to be removed from the collection, then there is * one and only one value that can be removed, even if there are other * elements which are equal to it. *

                  *

                  In most collection cases, elements are not distinguishable (equal is * equal), thus this method defaults to return false. In some cases, * however, they are. For example, the collection returned from the map's * values() collection view are backed by the map, so while there may be * two values that are equal, their associated keys are not. Since the * keys are distinguishable, the values are. *

                  *

                  This flag is used to skip some verifications for iterator.remove() * where it is impossible to perform an equivalent modification on the * confirmed collection because it is not possible to determine which * value in the confirmed collection to actually remove. Tests that * override the default (i.e. where equal elements are distinguishable), * should provide additional tests on iterator.remove() to make sure the * proper elements are removed when remove() is called on the iterator. */ public boolean areEqualElementsDistinguishable() { return false; } /** * Returns true if the collections15 produced by * {@link #makeCollection()} and {@link #makeFullCollection()} * support the add and addAll * operations.

                  * Default implementation returns true. Override if your collection * class does not support add or addAll. */ public boolean isAddSupported() { return true; } /** * Returns true if the collections15 produced by * {@link #makeCollection()} and {@link #makeFullCollection()} * support the remove, removeAll, * retainAll, clear and * iterator().remove() methods. * Default implementation returns true. Override if your collection * class does not support removal operations. */ public boolean isRemoveSupported() { return true; } /** * Returns true to indicate that the collection supports holding null. * The default implementation returns true; */ public boolean isNullSupported() { return true; } /** * Returns true to indicate that the collection supports fail fast iterators. * The default implementation returns true; */ public boolean isFailFastSupported() { return false; } /** * Returns true to indicate that the collection supports equals() comparisons. * This implementation returns false; */ public boolean isEqualsCheckable() { return false; } //----------------------------------------------------------------------- /** * Verifies that {@link #collection} and {@link #confirmed} have * identical state. */ public void verify() { int confirmedSize = confirmed.size(); assertEquals("Collection size should match confirmed collection's", confirmedSize, collection.size()); assertEquals("Collection isEmpty() result should match confirmed " + " collection's", confirmed.isEmpty(), collection.isEmpty()); // verify the collections15 are the same by attempting to match each // object in the collection and confirmed collection. To account for // duplicates and differing orders, each confirmed element is copied // into an array and a flag is maintained for each element to determine // whether it has been matched once and only once. If all elements in // the confirmed collection are matched once and only once and there // aren't any elements left to be matched in the collection, // verification is a success. // copy each collection value into an array Object[] confirmedValues = new Object[confirmedSize]; Iterator iter; iter = confirmed.iterator(); int pos = 0; while (iter.hasNext()) { confirmedValues[pos++] = iter.next(); } // allocate an array of boolean flags for tracking values that have // been matched once and only once. boolean[] matched = new boolean[confirmedSize]; // now iterate through the values of the collection and try to match // the value with one in the confirmed array. iter = collection.iterator(); while (iter.hasNext()) { Object o = iter.next(); boolean match = false; for (int i = 0; i < confirmedSize; i++) { if (matched[i]) { // skip values already matched continue; } if (o == confirmedValues[i] || (o != null && o.equals(confirmedValues[i]))) { // values matched matched[i] = true; match = true; break; } } // no match found! if (!match) { fail("Collection should not contain a value that the " + "confirmed collection does not have: " + o + "\nTest: " + collection + "\nReal: " + confirmed); } } // make sure there aren't any unmatched values for (int i = 0; i < confirmedSize; i++) { if (!matched[i]) { // the collection didn't match all the confirmed values fail("Collection should contain all values that are in the confirmed collection" + "\nTest: " + collection + "\nReal: " + confirmed); } } } //----------------------------------------------------------------------- /** * Resets the {@link #collection} and {@link #confirmed} fields to empty * collections15. Invoke this method before performing a modification * test. */ public void resetEmpty() { this.collection = makeCollection(); this.confirmed = makeConfirmedCollection(); } /** * Resets the {@link #collection} and {@link #confirmed} fields to full * collections15. Invoke this method before performing a modification * test. */ public void resetFull() { this.collection = makeFullCollection(); this.confirmed = makeConfirmedFullCollection(); } //----------------------------------------------------------------------- /** * Returns a confirmed empty collection. * For instance, an {@link java.util.ArrayList} for lists or a * {@link java.util.HashSet} for sets. * * @return a confirmed empty collection */ public abstract Collection makeConfirmedCollection(); /** * Returns a confirmed full collection. * For instance, an {@link java.util.ArrayList} for lists or a * {@link java.util.HashSet} for sets. The returned collection * should contain the elements returned by {@link #getFullElements()}. * * @return a confirmed full collection */ public abstract Collection makeConfirmedFullCollection(); /** * Return a new, empty {@link Collection} to be used for testing. */ public abstract Collection makeCollection(); /** * Returns a full collection to be used for testing. The collection * returned by this method should contain every element returned by * {@link #getFullElements()}. The default implementation, in fact, * simply invokes addAll on an empty collection with * the results of {@link #getFullElements()}. Override this default * if your collection doesn't support addAll. */ public Collection makeFullCollection() { Collection c = makeCollection(); c.addAll(Arrays.asList(getFullElements())); return c; } /** * Returns an empty collection for Object tests. */ public Object makeObject() { return makeCollection(); } /** * Makes an object to test add() type functions, override for specific typed collections15 that required * for example a MapEntry. * * @return */ public Object makeObjectToAdd() { return new Object(); } /** * Creates a new Map Entry that is independent of the first and the map. */ public Map.Entry cloneMapEntry(Map.Entry entry) { HashMap map = new HashMap(); map.put(entry.getKey(), entry.getValue()); return (Map.Entry) map.entrySet().iterator().next(); } //----------------------------------------------------------------------- /** * Returns an array of objects that are contained in a collection * produced by {@link #makeFullCollection()}. Every element in the * returned array must be an element in a full collection.

                  * The default implementation returns a heterogenous array of * objects with some duplicates. null is added if allowed. * Override if you require specific testing elements. Note that if you * override {@link #makeFullCollection()}, you must override * this method to reflect the contents of a full collection. */ public Object[] getFullElements() { if (isNullSupported()) { ArrayList list = new ArrayList(); list.addAll(Arrays.asList(getFullNonNullElements())); list.add(4, null); return list.toArray(); } else { return (Object[]) getFullNonNullElements().clone(); } } /** * Returns an array of elements that are not contained in a * full collection. Every element in the returned array must * not exist in a collection returned by {@link #makeFullCollection()}. * The default implementation returns a heterogenous array of elements * without null. Note that some of the tests add these elements * to an empty or full collection, so if your collection restricts * certain kinds of elements, you should override this method. */ public Object[] getOtherElements() { return getOtherNonNullElements(); } //----------------------------------------------------------------------- /** * Returns a list of elements suitable for return by * {@link #getFullElements()}. The array returned by this method * does not include null, but does include a variety of objects * of different types. Override getFullElements to return * the results of this method if your collection does not support * the null element. */ public Object[] getFullNonNullElements() { return new Object[]{new String(""), new String("One"), new Integer(2), "Three", new Integer(4), "One", new Double(5), new Float(6), "Seven", "Eight", new String("Nine"), new Integer(10), new Short((short) 11), new Long(12), "Thirteen", "14", "15", new Byte((byte) 16)}; } /** * Returns the default list of objects returned by * {@link #getOtherElements()}. Includes many objects * of different types. */ public Object[] getOtherNonNullElements() { return new Object[]{new Integer(0), new Float(0), new Double(0), "Zero", new Short((short) 0), new Byte((byte) 0), new Long(0), new Character('\u0000'), "0"}; } /** * Returns a list of string elements suitable for return by * {@link #getFullElements()}. Override getFullElements to return * the results of this method if your collection does not support * heterogenous elements or the null element. */ public Object[] getFullNonNullStringElements() { return new Object[]{"If", "the", "dull", "substance", "of", "my", "flesh", "were", "thought", "Injurious", "distance", "could", "not", "stop", "my", "way", }; } /** * Returns a list of string elements suitable for return by * {@link #getOtherElements()}. Override getOtherElements to return * the results of this method if your collection does not support * heterogenous elements or the null element. */ public Object[] getOtherNonNullStringElements() { return new Object[]{"For", "then", "despite", /* of */"space", "I", "would", "be", "brought", "From", "limits", "far", "remote", "where", "thou", "dost", "stay"}; } // Tests //----------------------------------------------------------------------- /** * Tests {@link Collection#add(Object)}. */ public void testCollectionAdd() { if (!isAddSupported()) return; Object[] elements = getFullElements(); for (int i = 0; i < elements.length; i++) { resetEmpty(); boolean r = collection.add(elements[i]); confirmed.add(elements[i]); verify(); assertTrue("Empty collection changed after add", r); assertEquals("Collection size is 1 after first add", 1, collection.size()); } resetEmpty(); int size = 0; for (int i = 0; i < elements.length; i++) { boolean r = collection.add(elements[i]); confirmed.add(elements[i]); verify(); if (r) size++; assertEquals("Collection size should grow after add", size, collection.size()); assertTrue("Collection should contain added element", collection.contains(elements[i])); } } /** * Tests {@link Collection#addAll(Collection)}. */ public void testCollectionAddAll() { if (!isAddSupported()) return; resetEmpty(); Object[] elements = getFullElements(); boolean r = collection.addAll(Arrays.asList(elements)); confirmed.addAll(Arrays.asList(elements)); verify(); assertTrue("Empty collection should change after addAll", r); for (int i = 0; i < elements.length; i++) { assertTrue("Collection should contain added element", collection.contains(elements[i])); } resetFull(); int size = collection.size(); elements = getOtherElements(); r = collection.addAll(Arrays.asList(elements)); confirmed.addAll(Arrays.asList(elements)); verify(); assertTrue("Full collection should change after addAll", r); for (int i = 0; i < elements.length; i++) { assertTrue("Full collection should contain added element", collection.contains(elements[i])); } assertEquals("Size should increase after addAll", size + elements.length, collection.size()); resetFull(); size = collection.size(); r = collection.addAll(Arrays.asList(getFullElements())); confirmed.addAll(Arrays.asList(getFullElements())); verify(); if (r) { assertTrue("Size should increase if addAll returns true", size < collection.size()); } else { assertEquals("Size should not change if addAll returns false", size, collection.size()); } } /** * If {@link #isAddSupported()} returns false, tests that add operations * raise UnsupportedOperationException. */ public void testUnsupportedAdd() { if (isAddSupported()) return; // GenericsNote: This is terrible, but I'm a little overwhelmed by the test classes at the moment and can't figure out how to do it correctly Map test = new HashMap(); test.put("test", "test"); Map.Entry entry = test.entrySet().iterator().next(); resetEmpty(); try { collection.add(entry); fail("Emtpy collection should not support add."); } catch (UnsupportedOperationException e) { // expected } // make sure things didn't change even if the expected exception was // thrown. verify(); try { collection.addAll(Arrays.asList(getFullElements())); fail("Emtpy collection should not support addAll."); } catch (UnsupportedOperationException e) { // expected } // make sure things didn't change even if the expected exception was // thrown. verify(); resetFull(); try { collection.add(entry); fail("Full collection should not support add."); } catch (UnsupportedOperationException e) { // expected } // make sure things didn't change even if the expected exception was // thrown. verify(); try { collection.addAll(Arrays.asList(getOtherElements())); fail("Full collection should not support addAll."); } catch (UnsupportedOperationException e) { // expected } // make sure things didn't change even if the expected exception was // thrown. verify(); } /** * Test {@link Collection#clear()}. */ public void testCollectionClear() { if (!isRemoveSupported()) return; resetEmpty(); collection.clear(); // just to make sure it doesn't raise anything verify(); resetFull(); collection.clear(); confirmed.clear(); verify(); } /** * Tests {@link Collection#contains(Object)}. */ public void testCollectionContains() { Object[] elements; resetEmpty(); elements = getFullElements(); for (int i = 0; i < elements.length; i++) { assertTrue("Empty collection shouldn't contain element[" + i + "]", !collection.contains(elements[i])); } // make sure calls to "contains" don't change anything verify(); elements = getOtherElements(); for (int i = 0; i < elements.length; i++) { assertTrue("Empty collection shouldn't contain element[" + i + "]", !collection.contains(elements[i])); } // make sure calls to "contains" don't change anything verify(); resetFull(); elements = getFullElements(); for (int i = 0; i < elements.length; i++) { assertTrue("Full collection should contain element[" + i + "]", collection.contains(elements[i])); } // make sure calls to "contains" don't change anything verify(); resetFull(); elements = getOtherElements(); for (int i = 0; i < elements.length; i++) { assertTrue("Full collection shouldn't contain element", !collection.contains(elements[i])); } } /** * Tests {@link Collection#containsAll(Collection)}. */ public void testCollectionContainsAll() { resetEmpty(); Collection col = new HashSet(); assertTrue("Every Collection should contain all elements of an " + "empty Collection.", collection.containsAll(col)); col.addAll(Arrays.asList(getOtherElements())); assertTrue("Empty Collection shouldn't contain all elements of " + "a non-empty Collection.", !collection.containsAll(col)); // make sure calls to "containsAll" don't change anything verify(); resetFull(); assertTrue("Full collection shouldn't contain other elements", !collection.containsAll(col)); col.clear(); col.addAll(Arrays.asList(getFullElements())); assertTrue("Full collection should containAll full elements", collection.containsAll(col)); // make sure calls to "containsAll" don't change anything verify(); int min = (getFullElements().length < 2 ? 0 : 2); int max = (getFullElements().length == 1 ? 1 : (getFullElements().length <= 5 ? getFullElements().length - 1 : 5)); col = Arrays.asList(getFullElements()).subList(min, max); assertTrue("Full collection should containAll partial full " + "elements", collection.containsAll(col)); assertTrue("Full collection should containAll itself", collection.containsAll(collection)); // make sure calls to "containsAll" don't change anything verify(); col = new ArrayList(); col.addAll(Arrays.asList(getFullElements())); col.addAll(Arrays.asList(getFullElements())); assertTrue("Full collection should containAll duplicate full " + "elements", collection.containsAll(col)); // make sure calls to "containsAll" don't change anything verify(); } /** * Tests {@link Collection#isEmpty()}. */ public void testCollectionIsEmpty() { resetEmpty(); assertEquals("New Collection should be empty.", true, collection.isEmpty()); // make sure calls to "isEmpty() don't change anything verify(); resetFull(); assertEquals("Full collection shouldn't be empty", false, collection.isEmpty()); // make sure calls to "isEmpty() don't change anything verify(); } /** * Tests the read-only functionality of {@link Collection#iterator()}. */ public void testCollectionIterator() { resetEmpty(); Iterator it1 = collection.iterator(); assertEquals("Iterator for empty Collection shouldn't have next.", false, it1.hasNext()); try { it1.next(); fail("Iterator at end of Collection should throw " + "NoSuchElementException when next is called."); } catch (NoSuchElementException e) { // expected } // make sure nothing has changed after non-modification verify(); resetFull(); it1 = collection.iterator(); for (int i = 0; i < collection.size(); i++) { assertTrue("Iterator for full collection should haveNext", it1.hasNext()); it1.next(); } assertTrue("Iterator should be finished", !it1.hasNext()); ArrayList list = new ArrayList(); it1 = collection.iterator(); for (int i = 0; i < collection.size(); i++) { Object next = it1.next(); assertTrue("Collection should contain element returned by " + "its iterator", collection.contains(next)); list.add(next); } try { it1.next(); fail("iterator.next() should raise NoSuchElementException " + "after it finishes"); } catch (NoSuchElementException e) { // expected } // make sure nothing has changed after non-modification verify(); } /** * Tests removals from {@link Collection#iterator()}. */ public void testCollectionIteratorRemove() { if (!isRemoveSupported()) return; resetEmpty(); try { collection.iterator().remove(); fail("New iterator.remove should raise IllegalState"); } catch (IllegalStateException e) { // expected } verify(); try { Iterator iter = collection.iterator(); iter.hasNext(); iter.remove(); fail("New iterator.remove should raise IllegalState " + "even after hasNext"); } catch (IllegalStateException e) { // expected } verify(); resetFull(); int size = collection.size(); Iterator iter = collection.iterator(); while (iter.hasNext()) { Object o = iter.next(); // TreeMap reuses the Map Entry, so the verify below fails // Clone it here if necessary if (o instanceof Map.Entry) { o = cloneMapEntry((Map.Entry) o); } iter.remove(); // if the elements aren't distinguishable, we can just remove a // matching element from the confirmed collection and verify // contents are still the same. Otherwise, we don't have the // ability to distinguish the elements and determine which to // remove from the confirmed collection (in which case, we don't // verify because we don't know how). // // see areEqualElementsDistinguishable() if (!areEqualElementsDistinguishable()) { confirmed.remove(o); verify(); } size--; assertEquals("Collection should shrink by one after " + "iterator.remove", size, collection.size()); } assertTrue("Collection should be empty after iterator purge", collection.isEmpty()); resetFull(); iter = collection.iterator(); iter.next(); iter.remove(); try { iter.remove(); fail("Second iter.remove should raise IllegalState"); } catch (IllegalStateException e) { // expected } } /** * Tests {@link Collection#remove(Object)}. */ public void testCollectionRemove() { if (!isRemoveSupported()) return; resetEmpty(); Object[] elements = getFullElements(); for (int i = 0; i < elements.length; i++) { assertTrue("Shouldn't remove nonexistent element", !collection.remove(elements[i])); verify(); } Object[] other = getOtherElements(); resetFull(); for (int i = 0; i < other.length; i++) { assertTrue("Shouldn't remove nonexistent other element", !collection.remove(other[i])); verify(); } int size = collection.size(); for (int i = 0; i < elements.length; i++) { resetFull(); assertTrue("Collection should remove extant element: " + elements[i], collection.remove(elements[i])); // if the elements aren't distinguishable, we can just remove a // matching element from the confirmed collection and verify // contents are still the same. Otherwise, we don't have the // ability to distinguish the elements and determine which to // remove from the confirmed collection (in which case, we don't // verify because we don't know how). // // see areEqualElementsDistinguishable() if (!areEqualElementsDistinguishable()) { confirmed.remove(elements[i]); verify(); } assertEquals("Collection should shrink after remove", size - 1, collection.size()); } } /** * Tests {@link Collection#removeAll(Collection)}. */ public void testCollectionRemoveAll() { if (!isRemoveSupported()) return; resetEmpty(); assertTrue("Emtpy collection removeAll should return false for " + "empty input", !collection.removeAll(Collections.EMPTY_SET)); verify(); assertTrue("Emtpy collection removeAll should return false for " + "nonempty input", !collection.removeAll(new ArrayList(collection))); verify(); resetFull(); assertTrue("Full collection removeAll should return false for " + "empty input", !collection.removeAll(Collections.EMPTY_SET)); verify(); assertTrue("Full collection removeAll should return false for other elements", !collection.removeAll(Arrays.asList(getOtherElements()))); verify(); assertTrue("Full collection removeAll should return true for full elements", collection.removeAll(new HashSet(collection))); confirmed.removeAll(new HashSet(confirmed)); verify(); resetFull(); int size = collection.size(); int min = (getFullElements().length < 2 ? 0 : 2); int max = (getFullElements().length == 1 ? 1 : (getFullElements().length <= 5 ? getFullElements().length - 1 : 5)); Collection all = Arrays.asList(getFullElements()).subList(min, max); assertTrue("Full collection removeAll should work", collection.removeAll(all)); confirmed.removeAll(all); verify(); assertTrue("Collection should shrink after removeAll", collection.size() < size); Iterator iter = all.iterator(); while (iter.hasNext()) { assertTrue("Collection shouldn't contain removed element", !collection.contains(iter.next())); } } /** * Tests {@link Collection#retainAll(Collection)}. */ public void testCollectionRetainAll() { if (!isRemoveSupported()) return; resetEmpty(); List elements = Arrays.asList(getFullElements()); List other = Arrays.asList(getOtherElements()); assertTrue("Empty retainAll() should return false", !collection.retainAll(Collections.EMPTY_SET)); verify(); assertTrue("Empty retainAll() should return false", !collection.retainAll(elements)); verify(); resetFull(); assertTrue("Collection should change from retainAll empty", collection.retainAll(Collections.EMPTY_SET)); confirmed.retainAll(Collections.EMPTY_SET); verify(); resetFull(); assertTrue("Collection changed from retainAll other", collection.retainAll(other)); confirmed.retainAll(other); verify(); resetFull(); int size = collection.size(); assertTrue("Collection shouldn't change from retainAll elements", !collection.retainAll(elements)); verify(); assertEquals("Collection size shouldn't change", size, collection.size()); if (getFullElements().length > 1) { resetFull(); size = collection.size(); int min = (getFullElements().length < 2 ? 0 : 2); int max = (getFullElements().length <= 5 ? getFullElements().length - 1 : 5); assertTrue("Collection should changed by partial retainAll", collection.retainAll(elements.subList(min, max))); confirmed.retainAll(elements.subList(min, max)); verify(); Iterator iter = collection.iterator(); while (iter.hasNext()) { assertTrue("Collection only contains retained element", elements.subList(min, max).contains(iter.next())); } } resetFull(); HashSet set = new HashSet(elements); size = collection.size(); assertTrue("Collection shouldn't change from retainAll without " + "duplicate elements", !collection.retainAll(set)); verify(); assertEquals("Collection size didn't change from nonduplicate " + "retainAll", size, collection.size()); } /** * Tests {@link Collection#size()}. */ public void testCollectionSize() { resetEmpty(); assertEquals("Size of new Collection is 0.", 0, collection.size()); resetFull(); assertTrue("Size of full collection should be greater than zero", collection.size() > 0); } /** * Tests {@link Collection#toArray()}. */ public void testCollectionToArray() { resetEmpty(); assertEquals("Empty Collection should return empty array for toArray", 0, collection.toArray().length); resetFull(); Object[] array = collection.toArray(); assertEquals("Full collection toArray should be same size as " + "collection", array.length, collection.size()); Object[] confirmedArray = confirmed.toArray(); assertEquals("length of array from confirmed collection should " + "match the length of the collection's array", confirmedArray.length, array.length); boolean[] matched = new boolean[array.length]; for (int i = 0; i < array.length; i++) { assertTrue("Collection should contain element in toArray", collection.contains(array[i])); boolean match = false; // find a match in the confirmed array for (int j = 0; j < array.length; j++) { // skip already matched if (matched[j]) continue; if (array[i] == confirmedArray[j] || (array[i] != null && array[i].equals(confirmedArray[j]))) { matched[j] = true; match = true; break; } } if (!match) { fail("element " + i + " in returned array should be found " + "in the confirmed collection's array"); } } for (int i = 0; i < matched.length; i++) { assertEquals("Collection should return all its elements in " + "toArray", true, matched[i]); } } /** * Tests {@link Collection#toArray(Object[])}. */ public void testCollectionToArray2() { resetEmpty(); Object[] a = new Object[]{new Object(), null, null}; Object[] array = collection.toArray(a); assertEquals("Given array shouldn't shrink", array, a); assertEquals("Last element should be set to null", a[0], null); verify(); resetFull(); try { array = collection.toArray(new Void[0]); fail("toArray(new Void[0]) should raise ArrayStore"); } catch (ArrayStoreException e) { // expected } verify(); try { array = collection.toArray(null); fail("toArray(null) should raise NPE"); } catch (NullPointerException e) { // expected } verify(); array = collection.toArray(new Object[0]); a = collection.toArray(); assertEquals("toArrays should be equal", Arrays.asList(array), Arrays.asList(a)); // Figure out if they're all the same class // TODO: It'd be nicer to detect a common superclass HashSet classes = new HashSet(); for (int i = 0; i < array.length; i++) { classes.add((array[i] == null) ? null : array[i].getClass()); } if (classes.size() > 1) return; Class cl = (Class) classes.iterator().next(); if (Map.Entry.class.isAssignableFrom(cl)) { // check needed for protective cases like Predicated/Unmod map entrySet cl = Map.Entry.class; } a = (Object[]) Array.newInstance(cl, 0); array = collection.toArray(a); assertEquals("toArray(Object[]) should return correct array type", a.getClass(), array.getClass()); assertEquals("type-specific toArrays should be equal", Arrays.asList(array), Arrays.asList(collection.toArray())); verify(); } /** * Tests toString on a collection. */ public void testCollectionToString() { resetEmpty(); assertTrue("toString shouldn't return null", collection.toString() != null); resetFull(); assertTrue("toString shouldn't return null", collection.toString() != null); } /** * If isRemoveSupported() returns false, tests to see that remove * operations raise an UnsupportedOperationException. */ public void testUnsupportedRemove() { if (isRemoveSupported()) return; resetEmpty(); try { collection.clear(); fail("clear should raise UnsupportedOperationException"); } catch (UnsupportedOperationException e) { // expected } verify(); try { collection.remove(null); fail("remove should raise UnsupportedOperationException"); } catch (UnsupportedOperationException e) { // expected } verify(); try { collection.removeAll(null); fail("removeAll should raise UnsupportedOperationException"); } catch (UnsupportedOperationException e) { // expected } verify(); try { collection.retainAll(null); fail("removeAll should raise UnsupportedOperationException"); } catch (UnsupportedOperationException e) { // expected } verify(); resetFull(); try { Iterator iterator = collection.iterator(); iterator.next(); iterator.remove(); fail("iterator.remove should raise UnsupportedOperationException"); } catch (UnsupportedOperationException e) { // expected } verify(); } /** * Tests that the collection's iterator is fail-fast. */ public void testCollectionIteratorFailFast() { if (!isFailFastSupported()) return; if (isAddSupported()) { resetFull(); try { Iterator iter = collection.iterator(); Object o = getOtherElements()[0]; collection.add(o); confirmed.add(o); iter.next(); fail("next after add should raise ConcurrentModification"); } catch (ConcurrentModificationException e) { // expected } verify(); resetFull(); try { Iterator iter = collection.iterator(); collection.addAll(Arrays.asList(getOtherElements())); confirmed.addAll(Arrays.asList(getOtherElements())); iter.next(); fail("next after addAll should raise ConcurrentModification"); } catch (ConcurrentModificationException e) { // expected } verify(); } if (!isRemoveSupported()) return; resetFull(); try { Iterator iter = collection.iterator(); collection.clear(); iter.next(); fail("next after clear should raise ConcurrentModification"); } catch (ConcurrentModificationException e) { // expected } catch (NoSuchElementException e) { // (also legal given spec) } resetFull(); try { Iterator iter = collection.iterator(); collection.remove(getFullElements()[0]); iter.next(); fail("next after remove should raise ConcurrentModification"); } catch (ConcurrentModificationException e) { // expected } resetFull(); try { Iterator iter = collection.iterator(); List sublist = Arrays.asList(getFullElements()).subList(2, 5); collection.removeAll(sublist); iter.next(); fail("next after removeAll should raise ConcurrentModification"); } catch (ConcurrentModificationException e) { // expected } resetFull(); try { Iterator iter = collection.iterator(); List sublist = Arrays.asList(getFullElements()).subList(2, 5); collection.retainAll(sublist); iter.next(); fail("next after retainAll should raise ConcurrentModification"); } catch (ConcurrentModificationException e) { // expected } } public void testSerializeDeserializeThenCompare() throws Exception { Object obj = makeCollection(); if (obj instanceof Serializable && isTestSerialization()) { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(buffer); out.writeObject(obj); out.close(); ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(buffer.toByteArray())); Object dest = in.readObject(); in.close(); if (isEqualsCheckable()) { assertEquals("obj != deserialize(serialize(obj)) - EMPTY Collection", obj, dest); } } obj = makeFullCollection(); if (obj instanceof Serializable && isTestSerialization()) { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(buffer); out.writeObject(obj); out.close(); ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(buffer.toByteArray())); Object dest = in.readObject(); in.close(); if (isEqualsCheckable()) { assertEquals("obj != deserialize(serialize(obj)) - FULL Collection", obj, dest); } } } } collections-generic-4.01/src/test/org/apache/commons/collections15/collection/TestAll.java0000644000175000017500000000314610464140757032073 0ustar giovannigiovanni/* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.collection; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * Entry point for tests. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 19:11:58 $ * @since Commons Collections 3.0 */ public class TestAll extends TestCase { public TestAll(String testName) { super(testName); } public static void main(String args[]) { String[] testCaseName = {TestAll.class.getName()}; junit.textui.TestRunner.main(testCaseName); } public static Test suite() { TestSuite suite = new TestSuite(); suite.addTest(TestCompositeCollection.suite()); suite.addTest(TestPredicatedCollection.suite()); suite.addTest(TestSynchronizedCollection.suite()); suite.addTest(TestTransformedCollection.suite()); suite.addTest(TestUnmodifiableCollection.suite()); return suite; } } ././@LongLink0000000000000000000000000000015500000000000011566 Lustar rootrootcollections-generic-4.01/src/test/org/apache/commons/collections15/collection/TestTransformedCollection.javacollections-generic-4.01/src/test/org/apache/commons/collections15/collection/TestTransformedCollect0000644000175000017500000001015610464140755034232 0ustar giovannigiovanni/* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.collection; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.collections15.Transformer; import org.apache.commons.collections15.TransformerUtils; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; /** * Extension of {@link TestCollection} for exercising the {@link TransformedCollection} * implementation. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 19:11:58 $ * @since Commons Collections 3.0 */ public class TestTransformedCollection extends AbstractTestCollection { private static class StringToInteger implements Transformer { public Object transform(Object input) { return new Integer((String) input); } } public static final Transformer NOOP_TRANSFORMER = TransformerUtils.nopTransformer(); public static final Transformer STRING_TO_INTEGER_TRANSFORMER = new StringToInteger(); public TestTransformedCollection(String testName) { super(testName); } public static Test suite() { return new TestSuite(TestTransformedCollection.class); } public static void main(String args[]) { String[] testCaseName = {TestTransformedCollection.class.getName()}; junit.textui.TestRunner.main(testCaseName); } //----------------------------------------------------------------------- public Collection makeConfirmedCollection() { return new ArrayList(); } public Collection makeConfirmedFullCollection() { List list = new ArrayList(); list.addAll(Arrays.asList(getFullElements())); return list; } public Collection makeCollection() { return TransformedCollection.decorate(new ArrayList(), NOOP_TRANSFORMER); } public Collection makeFullCollection() { List list = new ArrayList(); list.addAll(Arrays.asList(getFullElements())); return TransformedCollection.decorate(list, NOOP_TRANSFORMER); } //----------------------------------------------------------------------- public Object[] getFullElements() { return new Object[]{"1", "3", "5", "7", "2", "4", "6"}; } public Object[] getOtherElements() { return new Object[]{"9", "88", "678", "87", "98", "78", "99"}; } //----------------------------------------------------------------------- public void testTransformedCollection() { Collection coll = TransformedCollection.decorate(new ArrayList(), STRING_TO_INTEGER_TRANSFORMER); assertEquals(0, coll.size()); Object[] els = getFullElements(); for (int i = 0; i < els.length; i++) { coll.add(els[i]); assertEquals(i + 1, coll.size()); assertEquals(true, coll.contains(new Integer((String) els[i]))); assertEquals(false, coll.contains(els[i])); } assertEquals(true, coll.remove(new Integer((String) els[0]))); } public String getCompatibilityVersion() { return "3.1"; } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk((java.io.Serializable) collection, "D:/dev/collections15/data/test/TransformedCollection.emptyCollection.version3.1.obj"); // resetFull(); // writeExternalFormToDisk((java.io.Serializable) collection, "D:/dev/collections15/data/test/TransformedCollection.fullCollection.version3.1.obj"); // } } ././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootcollections-generic-4.01/src/test/org/apache/commons/collections15/collection/TestCompositeCollection.javacollections-generic-4.01/src/test/org/apache/commons/collections15/collection/TestCompositeCollectio0000644000175000017500000002413710464140754034243 0ustar giovannigiovanni/* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.collection; import junit.framework.Test; import junit.framework.TestSuite; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; /** * Extension of {@link AbstractTestCollection} for exercising the * {@link CompositeCollection} implementation. * * @author Brian McCallister * @author Matt Hall, John Watkinson, Phil Steitz * @version $Revision: 1.1 $ $Date: 2005/10/11 19:11:58 $ * @since Commons Collections 3.0 */ public class TestCompositeCollection extends AbstractTestCollection { public TestCompositeCollection(String name) { super(name); } public static Test suite() { return new TestSuite(TestCompositeCollection.class); } public static void main(String args[]) { String[] testCaseName = {TestCompositeCollection.class.getName()}; junit.textui.TestRunner.main(testCaseName); } //----------------------------------------------------------------------------- /** * Run stock collection tests without Mutator, so turn off add, remove */ public boolean isAddSupported() { return false; } public boolean isRemoveSupported() { return false; } /** * Empty collection is empty composite */ public Collection makeCollection() { return new CompositeCollection(); } public Collection makeConfirmedCollection() { return new HashSet(); } public Object[] getFullElements() { return new Object[]{"1", "2", "3", "4"}; } /** * Full collection consists of 4 collections15, each with one element */ public Collection makeFullCollection() { CompositeCollection compositeCollection = new CompositeCollection(); Object[] elements = getFullElements(); for (int i = 0; i < elements.length; i++) { Collection summand = new HashSet(); summand.add(elements[i]); compositeCollection.addComposited(summand); } return compositeCollection; } /** * Full collection should look like a collection with 4 elements */ public Collection makeConfirmedFullCollection() { Collection collection = new HashSet(); collection.addAll(Arrays.asList(getFullElements())); return collection; } /** * Override testUnsupportedRemove, since the default impl expects removeAll, * retainAll and iterator().remove to throw */ public void testUnsupportedRemove() { resetFull(); try { collection.remove(null); fail("remove should raise UnsupportedOperationException"); } catch (UnsupportedOperationException e) { // expected } verify(); } //-------------------------------------------------------------------------- protected CompositeCollection c; protected Collection one; protected Collection two; protected void setUpTest() { c = new CompositeCollection(); one = new HashSet(); two = new HashSet(); } protected void setUpMutatorTest() { setUpTest(); c.setMutator(new CompositeCollection.CollectionMutator() { public boolean add(CompositeCollection composite, Collection[] collections, Object obj) { for (int i = 0; i < collections.length; i++) { collections[i].add(obj); } return true; } public boolean addAll(CompositeCollection composite, Collection[] collections, Collection coll) { for (int i = 0; i < collections.length; i++) { collections[i].addAll(coll); } return true; } public boolean remove(CompositeCollection composite, Collection[] collections, Object obj) { for (int i = 0; i < collections.length; i++) { collections[i].remove(obj); } return true; } }); } public void testSize() { setUpTest(); HashSet set = new HashSet(); set.add("a"); set.add("b"); c.addComposited(set); assertEquals(set.size(), c.size()); } public void testMultipleCollectionsSize() { setUpTest(); HashSet set = new HashSet(); set.add("a"); set.add("b"); c.addComposited(set); HashSet other = new HashSet(); other.add("c"); c.addComposited(other); assertEquals(set.size() + other.size(), c.size()); } public void testIsEmpty() { setUpTest(); assertTrue(c.isEmpty()); HashSet empty = new HashSet(); c.addComposited(empty); assertTrue(c.isEmpty()); empty.add("a"); assertTrue(!c.isEmpty()); } public void testIterator() { setUpTest(); one.add("1"); two.add("2"); c.addComposited(one); c.addComposited(two); Iterator i = c.iterator(); Object next = i.next(); assertTrue(c.contains(next)); assertTrue(one.contains(next)); next = i.next(); i.remove(); assertTrue(!c.contains(next)); assertTrue(!two.contains(next)); } public void testClear() { setUpTest(); one.add("1"); two.add("2"); c.addComposited(one, two); c.clear(); assertTrue(one.isEmpty()); assertTrue(two.isEmpty()); assertTrue(c.isEmpty()); } public void testContainsAll() { setUpTest(); one.add("1"); two.add("1"); c.addComposited(one); assertTrue(c.containsAll(two)); } public void testRetainAll() { setUpTest(); one.add("1"); one.add("2"); two.add("1"); c.addComposited(one); c.retainAll(two); assertTrue(!c.contains("2")); assertTrue(!one.contains("2")); assertTrue(c.contains("1")); assertTrue(one.contains("1")); } public void testAddAllMutator() { setUpTest(); c.setMutator(new CompositeCollection.CollectionMutator() { public boolean add(CompositeCollection composite, Collection[] collections, Object obj) { for (int i = 0; i < collections.length; i++) { collections[i].add(obj); } return true; } public boolean addAll(CompositeCollection composite, Collection[] collections, Collection coll) { for (int i = 0; i < collections.length; i++) { collections[i].addAll(coll); } return true; } public boolean remove(CompositeCollection composite, Collection[] collections, Object obj) { return false; } }); c.addComposited(one); two.add("foo"); c.addAll(two); assertTrue(c.contains("foo")); assertTrue(one.contains("foo")); } public void testAddMutator() { setUpTest(); c.setMutator(new CompositeCollection.CollectionMutator() { public boolean add(CompositeCollection composite, Collection[] collections, Object obj) { for (int i = 0; i < collections.length; i++) { collections[i].add(obj); } return true; } public boolean addAll(CompositeCollection composite, Collection[] collections, Collection coll) { for (int i = 0; i < collections.length; i++) { collections[i].addAll(coll); } return true; } public boolean remove(CompositeCollection composite, Collection[] collections, Object obj) { return false; } }); c.addComposited(one); c.add("foo"); assertTrue(c.contains("foo")); assertTrue(one.contains("foo")); } public void testToCollection() { setUpTest(); one.add("1"); two.add("2"); c.addComposited(one, two); Collection foo = c.toCollection(); assertTrue(foo.containsAll(c)); assertEquals(c.size(), foo.size()); one.add("3"); assertTrue(!foo.containsAll(c)); } public void testAddAllToCollection() { setUpTest(); one.add("1"); two.add("2"); c.addComposited(one, two); Collection toCollection = new HashSet(); toCollection.addAll(c); assertTrue(toCollection.containsAll(c)); assertEquals(c.size(), toCollection.size()); } public void testRemove() { setUpMutatorTest(); one.add("1"); two.add("2"); two.add("1"); c.addComposited(one, two); c.remove("1"); assertTrue(!c.contains("1")); assertTrue(!one.contains("1")); assertTrue(!two.contains("1")); } public void testRemoveAll() { setUpMutatorTest(); one.add("1"); two.add("2"); two.add("1"); c.addComposited(one, two); c.removeAll(one); assertTrue(!c.contains("1")); assertTrue(!one.contains("1")); assertTrue(!two.contains("1")); } public void testRemoveComposited() { setUpMutatorTest(); one.add("1"); two.add("2"); two.add("1"); c.addComposited(one, two); c.removeComposited(one); assertTrue(c.contains("1")); assertEquals(c.size(), 2); } } ././@LongLink0000000000000000000000000000015600000000000011567 Lustar rootrootcollections-generic-4.01/src/test/org/apache/commons/collections15/collection/TestUnmodifiableCollection.javacollections-generic-4.01/src/test/org/apache/commons/collections15/collection/TestUnmodifiableCollec0000644000175000017500000000561010464140761034154 0ustar giovannigiovanni/* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.collection; import junit.framework.Test; import junit.framework.TestSuite; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; /** * Extension of {@link AbstractTestCollection} for exercising the * {@link UnmodifiableCollection} implementation. * * @author Phil Steitz * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 19:11:58 $ * @since Commons Collections 3.0 */ public class TestUnmodifiableCollection extends AbstractTestCollection { public TestUnmodifiableCollection(String testName) { super(testName); } public static Test suite() { return new TestSuite(TestUnmodifiableCollection.class); } public static void main(String args[]) { String[] testCaseName = {TestUnmodifiableCollection.class.getName()}; junit.textui.TestRunner.main(testCaseName); } //----------------------------------------------------------------------- public Collection makeCollection() { return UnmodifiableCollection.decorate(new ArrayList()); } public Collection makeFullCollection() { List list = new ArrayList(); list.addAll(Arrays.asList(getFullElements())); return UnmodifiableCollection.decorate(list); } public Collection makeConfirmedCollection() { ArrayList list = new ArrayList(); return list; } public Collection makeConfirmedFullCollection() { ArrayList list = new ArrayList(); list.addAll(Arrays.asList(getFullElements())); return list; } public boolean isAddSupported() { return false; } public boolean isRemoveSupported() { return false; } public String getCompatibilityVersion() { return "3.1"; } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk((java.io.Serializable) collection, "D:/dev/collections15/data/test/UnmodifiableCollection.emptyCollection.version3.1.obj"); // resetFull(); // writeExternalFormToDisk((java.io.Serializable) collection, "D:/dev/collections15/data/test/UnmodifiableCollection.fullCollection.version3.1.obj"); // } } collections-generic-4.01/src/test/org/apache/commons/collections15/LocalTestNode.java0000644000175000017500000000523710464140756031072 0ustar giovannigiovanni/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15; /** * Class LocalTestNode, a helper class for TestDoubleOrderedMap * * @author Matt Hall, John Watkinson, Marc Johnson (marcj at users dot sourceforge dot net) * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:39 $ */ class LocalTestNode implements Comparable { private Comparable key; private Comparable value; /** * construct a LocalTestNode * * @param key value used to create the key and value */ LocalTestNode(final int key) { this.key = new Integer(key); this.value = String.valueOf(key); } /** * @param key the unique key associated with the current node. */ void setKey(Comparable key) { this.key = key; } /** * @return the unique key associated with the current node */ Comparable getKey() { return key; } /** * @param value the unique value associated with the current node. */ void setValue(Comparable value) { this.value = value; } /** * @return the unique value associated with the current node */ Comparable getValue() { return value; } /** * Method compareTo * * @param o * @return */ public int compareTo(Object o) { LocalTestNode other = (LocalTestNode) o; int rval = getKey().compareTo(other.getKey()); if (rval == 0) { rval = getValue().compareTo(other.getValue()); } return rval; } /** * Method equals * * @param o * @return true if equal */ public boolean equals(Object o) { if (o == null) { return false; } if (!(o.getClass().equals(this.getClass()))) { return false; } LocalTestNode node = (LocalTestNode) o; return (getKey().equals(node.getKey()) && getValue().equals(node.getValue())); } /** * @return hash code */ public int hashCode() { return getKey().hashCode() ^ getValue().hashCode(); } } collections-generic-4.01/src/test/org/apache/commons/collections15/TestFastTreeMap1.java0000644000175000017500000000314410464140756031461 0ustar giovannigiovanni/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15; import junit.framework.Test; import java.util.Map; import java.util.TreeMap; import org.apache.commons.collections15.map.FastTreeMap; /** * Test FastTreeMap in fast mode. * * @author Matt Hall, John Watkinson, Jason van Zyl * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:39 $ */ public class TestFastTreeMap1 extends TestFastTreeMap { public TestFastTreeMap1(String testName) { super(testName); } public static Test suite() { return BulkTest.makeSuite(TestFastTreeMap1.class); } public static void main(String args[]) { String[] testCaseName = {TestFastTreeMap1.class.getName()}; junit.textui.TestRunner.main(testCaseName); } public Map makeEmptyMap() { FastTreeMap ftm = new FastTreeMap(); ftm.setFast(true); return (ftm); } public void setUp() { map = (TreeMap) makeEmptyMap(); } } collections-generic-4.01/src/test/org/apache/commons/collections15/set/0000755000175000017500000000000011664401370026306 5ustar giovannigiovannicollections-generic-4.01/src/test/org/apache/commons/collections15/set/TestUnmodifiableSet.java0000644000175000017500000000467510464140764033103 0ustar giovannigiovanni/* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.set; import junit.framework.Test; import org.apache.commons.collections15.BulkTest; import java.util.Arrays; import java.util.HashSet; import java.util.Set; /** * Extension of {@link AbstractTestSet} for exercising the * {@link UnmodifiableSet} implementation. * * @author Matt Hall, John Watkinson, Phil Steitz * @version $Revision: 1.1 $ $Date: 2005/10/11 19:11:58 $ * @since Commons Collections 3.0 */ public class TestUnmodifiableSet extends AbstractTestSet { public TestUnmodifiableSet(String testName) { super(testName); } public static Test suite() { return BulkTest.makeSuite(TestUnmodifiableSet.class); } public static void main(String args[]) { String[] testCaseName = {TestUnmodifiableSet.class.getName()}; junit.textui.TestRunner.main(testCaseName); } //------------------------------------------------------------------- public Set makeEmptySet() { return UnmodifiableSet.decorate(new HashSet()); } public Set makeFullSet() { HashSet set = new HashSet(); set.addAll(Arrays.asList(getFullElements())); return UnmodifiableSet.decorate(set); } public boolean isAddSupported() { return false; } public boolean isRemoveSupported() { return false; } public String getCompatibilityVersion() { return "3.1"; } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk((java.io.Serializable) collection, "D:/dev/collections15/data/test/UnmodifiableSet.emptyCollection.version3.1.obj"); // resetFull(); // writeExternalFormToDisk((java.io.Serializable) collection, "D:/dev/collections15/data/test/UnmodifiableSet.fullCollection.version3.1.obj"); // } } collections-generic-4.01/src/test/org/apache/commons/collections15/set/AbstractTestSortedSet.java0000644000175000017500000002574510464140754033431 0ustar giovannigiovanni/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.set; import org.apache.commons.collections15.BulkTest; import java.util.*; /** * Abstract test class for {@link SortedSet} methods and contracts. *

                  * To use, subclass and override the {@link #makeEmptySet()} * method. You may have to override other protected methods if your * set is not modifiable, or if your set restricts what kinds of * elements may be added; see {@link AbstractTestCollection} for more details. * * @author Stephen Colebourne * @author Matt Hall, John Watkinson, Dieter Wimberger * @version $Revision: 1.1 $ $Date: 2005/10/11 19:11:58 $ * @since Commons Collections 3.0 */ public abstract class AbstractTestSortedSet extends AbstractTestSet { /** * JUnit constructor. * * @param name name for test */ public AbstractTestSortedSet(String name) { super(name); } //----------------------------------------------------------------------- /** * Verification extension, will check the order of elements, * the sets should already be verified equal. */ public void verify() { super.verify(); // Check that iterator returns elements in order and first() and last() // are consistent Iterator colliter = collection.iterator(); Iterator confiter = confirmed.iterator(); Object first = null; Object last = null; while (colliter.hasNext()) { if (first == null) { first = colliter.next(); last = first; } else { last = colliter.next(); } assertEquals("Element appears to be out of order.", last, confiter.next()); } if (collection.size() > 0) { assertEquals("Incorrect element returned by first().", first, ((SortedSet) collection).first()); assertEquals("Incorrect element returned by last().", last, ((SortedSet) collection).last()); } } //----------------------------------------------------------------------- /** * Overridden because SortedSets don't allow null elements (normally). * * @return false */ public boolean isNullSupported() { return false; } //----------------------------------------------------------------------- /** * Returns an empty {@link TreeSet} for use in modification testing. * * @return a confirmed empty collection */ public Collection makeConfirmedCollection() { return new TreeSet(); } //----------------------------------------------------------------------- /** * Return the {@link AbstractTestCollection#confirmed} fixture, but cast as a * SortedSet. */ public SortedSet getConfirmedSortedSet() { return (SortedSet) confirmed; } //----------------------------------------------------------------------- /** * Override to return comparable objects. */ public Object[] getFullNonNullElements() { Object[] elements = new Object[30]; for (int i = 0; i < 30; i++) { elements[i] = new Integer(i + i + 1); } return elements; } /** * Override to return comparable objects. */ public Object[] getOtherNonNullElements() { Object[] elements = new Object[30]; for (int i = 0; i < 30; i++) { elements[i] = new Integer(i + i + 2); } return elements; } //----------------------------------------------------------------------- /** * Bulk test {@link SortedSet#subSet(Object, Object)}. This method runs through all of * the tests in {@link AbstractTestSortedSet}. * After modification operations, {@link #verify()} is invoked to ensure * that the set and the other collection views are still valid. * * @return a {@link AbstractTestSet} instance for testing a subset. */ public BulkTest bulkTestSortedSetSubSet() { int length = getFullElements().length; int lobound = length / 3; int hibound = lobound * 2; return new TestSortedSetSubSet(lobound, hibound); } /** * Bulk test {@link SortedSet#headSet(Object)}. This method runs through all of * the tests in {@link AbstractTestSortedSet}. * After modification operations, {@link #verify()} is invoked to ensure * that the set and the other collection views are still valid. * * @return a {@link AbstractTestSet} instance for testing a headset. */ public BulkTest bulkTestSortedSetHeadSet() { int length = getFullElements().length; int lobound = length / 3; int hibound = lobound * 2; return new TestSortedSetSubSet(hibound, true); } /** * Bulk test {@link SortedSet#tailSet(Object)}. This method runs through all of * the tests in {@link AbstractTestSortedSet}. * After modification operations, {@link #verify()} is invoked to ensure * that the set and the other collection views are still valid. * * @return a {@link AbstractTestSet} instance for testing a tailset. */ public BulkTest bulkTestSortedSetTailSet() { int length = getFullElements().length; int lobound = length / 3; return new TestSortedSetSubSet(lobound, false); } public class TestSortedSetSubSet extends AbstractTestSortedSet { private int m_Type; private int m_LowBound; private int m_HighBound; private Object[] m_FullElements; private Object[] m_OtherElements; public TestSortedSetSubSet(int bound, boolean head) { super("TestSortedSetSubSet"); if (head) { //System.out.println("HEADSET"); m_Type = TYPE_HEADSET; m_HighBound = bound; m_FullElements = new Object[bound]; System.arraycopy(AbstractTestSortedSet.this.getFullElements(), 0, m_FullElements, 0, bound); m_OtherElements = new Object[bound - 1]; System.arraycopy(//src src_pos dst dst_pos length AbstractTestSortedSet.this.getOtherElements(), 0, m_OtherElements, 0, bound - 1); //System.out.println(new TreeSet(Arrays.asList(m_FullElements))); //System.out.println(new TreeSet(Arrays.asList(m_OtherElements))); } else { //System.out.println("TAILSET"); m_Type = TYPE_TAILSET; m_LowBound = bound; Object[] allelements = AbstractTestSortedSet.this.getFullElements(); //System.out.println("bound = "+bound +"::length="+allelements.length); m_FullElements = new Object[allelements.length - bound]; System.arraycopy(allelements, bound, m_FullElements, 0, allelements.length - bound); m_OtherElements = new Object[allelements.length - bound - 1]; System.arraycopy(//src src_pos dst dst_pos length AbstractTestSortedSet.this.getOtherElements(), bound, m_OtherElements, 0, allelements.length - bound - 1); //System.out.println(new TreeSet(Arrays.asList(m_FullElements))); //System.out.println(new TreeSet(Arrays.asList(m_OtherElements))); //resetFull(); //System.out.println(collection); //System.out.println(confirmed); } } //type public TestSortedSetSubSet(int lobound, int hibound) { super("TestSortedSetSubSet"); //System.out.println("SUBSET"); m_Type = TYPE_SUBSET; m_LowBound = lobound; m_HighBound = hibound; int length = hibound - lobound; //System.out.println("Low=" + lobound + "::High=" + hibound + "::Length=" + length); m_FullElements = new Object[length]; System.arraycopy(AbstractTestSortedSet.this.getFullElements(), lobound, m_FullElements, 0, length); m_OtherElements = new Object[length - 1]; System.arraycopy(//src src_pos dst dst_pos length AbstractTestSortedSet.this.getOtherElements(), lobound, m_OtherElements, 0, length - 1); //System.out.println(new TreeSet(Arrays.asList(m_FullElements))); //System.out.println(new TreeSet(Arrays.asList(m_OtherElements))); } public boolean isNullSupported() { return AbstractTestSortedSet.this.isNullSupported(); } public boolean isAddSupported() { return AbstractTestSortedSet.this.isAddSupported(); } public boolean isRemoveSupported() { return AbstractTestSortedSet.this.isRemoveSupported(); } public boolean isFailFastSupported() { return AbstractTestSortedSet.this.isFailFastSupported(); } public Object[] getFullElements() { return m_FullElements; } public Object[] getOtherElements() { return m_OtherElements; } private SortedSet getSubSet(SortedSet set) { Object[] elements = AbstractTestSortedSet.this.getFullElements(); switch (m_Type) { case TYPE_SUBSET: return set.subSet(elements[m_LowBound], elements[m_HighBound]); case TYPE_HEADSET: return set.headSet(elements[m_HighBound]); case TYPE_TAILSET: return set.tailSet(elements[m_LowBound]); default : return null; } } public Set makeEmptySet() { SortedSet s = (SortedSet) AbstractTestSortedSet.this.makeEmptySet(); return getSubSet(s); } public Set makeFullSet() { SortedSet s = (SortedSet) AbstractTestSortedSet.this.makeFullCollection(); return getSubSet(s); } public boolean isTestSerialization() { return false; } public BulkTest bulkTestSortedSetSubSet() { return null; // prevent infinite recursion } public BulkTest bulkTestSortedSetHeadSet() { return null; // prevent infinite recursion } public BulkTest bulkTestSortedSetTailSet() { return null; // prevent infinite recursion } static final int TYPE_SUBSET = 0; static final int TYPE_TAILSET = 1; static final int TYPE_HEADSET = 2; } } collections-generic-4.01/src/test/org/apache/commons/collections15/set/TestCompositeSet.java0000644000175000017500000001233310464140764032435 0ustar giovannigiovanni/* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.set; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.collections15.collection.CompositeCollection; import java.util.Collection; import java.util.HashSet; import java.util.Set; /** * Extension of {@link AbstractTestSet} for exercising the * {@link CompositeSet} implementation. * * @author Brian McCallister * @author Matt Hall, John Watkinson, Phil Steitz * @version $Revision: 1.1 $ $Date: 2005/10/11 19:11:58 $ * @since Commons Collections 3.0 */ public class TestCompositeSet extends AbstractTestSet { public TestCompositeSet(String name) { super(name); } public static Test suite() { return new TestSuite(TestCompositeSet.class); } public Set makeEmptySet() { final HashSet contained = new HashSet(); CompositeSet set = new CompositeSet(contained); set.setMutator(new CompositeSet.SetMutator() { public void resolveCollision(CompositeSet comp, Set existing, Set added, Collection intersects) { throw new IllegalArgumentException(); } public boolean add(CompositeCollection composite, Collection[] collections, Object obj) { return contained.add(obj); } public boolean addAll(CompositeCollection composite, Collection[] collections, Collection coll) { return contained.addAll(coll); } public boolean remove(CompositeCollection composite, Collection[] collections, Object obj) { return contained.remove(obj); } }); return set; } public Set buildOne() { HashSet set = new HashSet(); set.add("1"); set.add("2"); return set; } public Set buildTwo() { HashSet set = new HashSet(); set.add("3"); set.add("4"); return set; } public void testContains() { CompositeSet set = new CompositeSet(new Set[]{buildOne(), buildTwo()}); assertTrue(set.contains("1")); } public void testRemoveUnderlying() { Set one = buildOne(); Set two = buildTwo(); CompositeSet set = new CompositeSet(new Set[]{one, two}); one.remove("1"); assertFalse(set.contains("1")); two.remove("3"); assertFalse(set.contains("3")); } public void testRemoveComposited() { Set one = buildOne(); Set two = buildTwo(); CompositeSet set = new CompositeSet(new Set[]{one, two}); set.remove("1"); assertFalse(one.contains("1")); set.remove("3"); assertFalse(one.contains("3")); } public void testFailedCollisionResolution() { Set one = buildOne(); Set two = buildTwo(); CompositeSet set = new CompositeSet(new Set[]{one, two}); set.setMutator(new CompositeSet.SetMutator() { public void resolveCollision(CompositeSet comp, Set existing, Set added, Collection intersects) { } public boolean add(CompositeCollection composite, Collection[] collections, Object obj) { throw new UnsupportedOperationException(); } public boolean addAll(CompositeCollection composite, Collection[] collections, Collection coll) { throw new UnsupportedOperationException(); } public boolean remove(CompositeCollection composite, Collection[] collections, Object obj) { throw new UnsupportedOperationException(); } }); HashSet three = new HashSet(); three.add("1"); try { set.addComposited(three); fail("IllegalArgumentException should have been thrown"); } catch (IllegalArgumentException e) { // expected } } public void testAddComposited() { Set one = buildOne(); Set two = buildTwo(); CompositeSet set = new CompositeSet(); set.addComposited(one, two); CompositeSet set2 = new CompositeSet(buildOne()); set2.addComposited(buildTwo()); assertTrue(set.equals(set2)); HashSet set3 = new HashSet(); set3.add("1"); set3.add("2"); set3.add("3"); HashSet set4 = new HashSet(); set4.add("4"); CompositeSet set5 = new CompositeSet(set3); set5.addComposited(set4); assertTrue(set.equals(set5)); try { set.addComposited(set3); fail("Expecting UnsupportedOperationException."); } catch (UnsupportedOperationException ex) { // expected } } } collections-generic-4.01/src/test/org/apache/commons/collections15/set/TestMapBackedSet.java0000644000175000017500000000370210464140756032303 0ustar giovannigiovanni/* * Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.set; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.collections15.map.HashedMap; import java.util.Set; /** * JUnit test. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 19:11:58 $ * @since Commons Collections 3.1 */ public class TestMapBackedSet extends AbstractTestSet { public TestMapBackedSet(String testName) { super(testName); } public static Test suite() { return new TestSuite(TestMapBackedSet.class); } public static void main(String args[]) { String[] testCaseName = {TestMapBackedSet.class.getName()}; junit.textui.TestRunner.main(testCaseName); } public Set makeEmptySet() { return MapBackedSet.decorate(new HashedMap()); } public String getCompatibilityVersion() { return "3.1"; } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk((java.io.Serializable) collection, "D:/dev/collections15/data/test/MapBackedSet.emptyCollection.version3.1.obj"); // resetFull(); // writeExternalFormToDisk((java.io.Serializable) collection, "D:/dev/collections15/data/test/MapBackedSet.fullCollection.version3.1.obj"); // } } collections-generic-4.01/src/test/org/apache/commons/collections15/set/TestMapBackedSet2.java0000644000175000017500000000541010464140754032361 0ustar giovannigiovanni/* * Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.set; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.collections15.map.LinkedMap; import java.util.Iterator; import java.util.Set; /** * JUnit test. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 19:11:58 $ * @since Commons Collections 3.1 */ public class TestMapBackedSet2 extends AbstractTestSet { public TestMapBackedSet2(String testName) { super(testName); } public static Test suite() { return new TestSuite(TestMapBackedSet2.class); } public static void main(String args[]) { String[] testCaseName = {TestMapBackedSet2.class.getName()}; junit.textui.TestRunner.main(testCaseName); } public Set makeEmptySet() { return MapBackedSet.decorate(new LinkedMap()); } protected Set setupSet() { Set set = makeEmptySet(); for (int i = 0; i < 10; i++) { set.add(Integer.toString(i)); } return set; } public void testOrdering() { Set set = setupSet(); Iterator it = set.iterator(); for (int i = 0; i < 10; i++) { assertEquals("Sequence is wrong", Integer.toString(i), it.next()); } for (int i = 0; i < 10; i += 2) { assertTrue("Must be able to remove int", set.remove(Integer.toString(i))); } it = set.iterator(); for (int i = 1; i < 10; i += 2) { assertEquals("Sequence is wrong after remove ", Integer.toString(i), it.next()); } for (int i = 0; i < 10; i++) { set.add(Integer.toString(i)); } assertEquals("Size of set is wrong!", 10, set.size()); it = set.iterator(); for (int i = 1; i < 10; i += 2) { assertEquals("Sequence is wrong", Integer.toString(i), it.next()); } for (int i = 0; i < 10; i += 2) { assertEquals("Sequence is wrong", Integer.toString(i), it.next()); } } public void testCanonicalEmptyCollectionExists() { } public void testCanonicalFullCollectionExists() { } } collections-generic-4.01/src/test/org/apache/commons/collections15/set/AbstractTestSet.java0000644000175000017500000001307410464140761032236 0ustar giovannigiovanni/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.set; import org.apache.commons.collections15.collection.AbstractTestCollection; import java.util.*; /** * Abstract test class for {@link Set} methods and contracts. *

                  * Since {@link Set} doesn't stipulate much new behavior that isn't already * found in {@link Collection}, this class basically just adds tests for * {@link Set#equals} and {@link Set#hashCode()} along with an updated * {@link #verify()} that ensures elements do not appear more than once in the * set. *

                  * To use, subclass and override the {@link #makeEmptySet()} * method. You may have to override other protected methods if your * set is not modifiable, or if your set restricts what kinds of * elements may be added; see {@link AbstractTestCollection} for more details. * * @author Matt Hall, John Watkinson, Paul Jack * @version $Revision: 1.1 $ $Date: 2005/10/11 19:11:58 $ * @since Commons Collections 3.0 */ public abstract class AbstractTestSet extends AbstractTestCollection { /** * JUnit constructor. * * @param name name for test */ public AbstractTestSet(String name) { super(name); } //----------------------------------------------------------------------- /** * Provides additional verifications for sets. */ public void verify() { super.verify(); assertEquals("Sets should be equal", confirmed, collection); assertEquals("Sets should have equal hashCodes", confirmed.hashCode(), collection.hashCode()); Collection set = makeConfirmedCollection(); Iterator iterator = collection.iterator(); while (iterator.hasNext()) { assertTrue("Set.iterator should only return unique elements", set.add(iterator.next())); } } //----------------------------------------------------------------------- /** * Set equals method is defined. */ public boolean isEqualsCheckable() { return true; } /** * Returns an empty Set for use in modification testing. * * @return a confirmed empty collection */ public Collection makeConfirmedCollection() { return new HashSet(); } /** * Returns a full Set for use in modification testing. * * @return a confirmed full collection */ public Collection makeConfirmedFullCollection() { Collection set = makeConfirmedCollection(); set.addAll(Arrays.asList(getFullElements())); return set; } /** * Makes an empty set. The returned set should have no elements. * * @return an empty set */ public abstract Set makeEmptySet(); /** * Makes a full set by first creating an empty set and then adding * all the elements returned by {@link #getFullElements()}. *

                  * Override if your set does not support the add operation. * * @return a full set */ public Set makeFullSet() { Set set = makeEmptySet(); set.addAll(Arrays.asList(getFullElements())); return set; } /** * Makes an empty collection by invoking {@link #makeEmptySet()}. * * @return an empty collection */ public final Collection makeCollection() { return makeEmptySet(); } /** * Makes a full collection by invoking {@link #makeFullSet()}. * * @return a full collection */ public final Collection makeFullCollection() { return makeFullSet(); } //----------------------------------------------------------------------- /** * Return the {@link AbstractTestCollection#collection} fixture, but cast as a Set. */ public Set getSet() { return (Set) collection; } /** * Return the {@link AbstractTestCollection#confirmed} fixture, but cast as a Set. */ public Set getConfirmedSet() { return (Set) confirmed; } //----------------------------------------------------------------------- /** * Tests {@link Set#equals(Object)}. */ public void testSetEquals() { resetEmpty(); assertEquals("Empty sets should be equal", getSet(), getConfirmedSet()); verify(); Collection set2 = makeConfirmedCollection(); set2.add("foo"); assertTrue("Empty set shouldn't equal nonempty set", !getSet().equals(set2)); resetFull(); assertEquals("Full sets should be equal", getSet(), getConfirmedSet()); verify(); set2.clear(); set2.addAll(Arrays.asList(getOtherElements())); assertTrue("Sets with different contents shouldn't be equal", !getSet().equals(set2)); } /** * Tests {@link Set#hashCode()}. */ public void testSetHashCode() { resetEmpty(); assertEquals("Empty sets have equal hashCodes", getSet().hashCode(), getConfirmedSet().hashCode()); resetFull(); assertEquals("Equal sets have equal hashCodes", getSet().hashCode(), getConfirmedSet().hashCode()); } } collections-generic-4.01/src/test/org/apache/commons/collections15/set/TestTypedSet.java0000644000175000017500000000341310464140764031557 0ustar giovannigiovanni/* * Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.set; import junit.framework.Test; import org.apache.commons.collections15.BulkTest; import java.util.HashSet; import java.util.Set; /** * Extension of {@link AbstractTestSet} for exercising the * {@link TypedSet} implementation. * * @author Matt Hall, John Watkinson, Phil Steitz * @version $Revision: 1.1 $ $Date: 2005/10/11 19:11:58 $ * @since Commons Collections 3.1 */ public class TestTypedSet extends AbstractTestSet { public TestTypedSet(String testName) { super(testName); } public static Test suite() { return BulkTest.makeSuite(TestTypedSet.class); } public static void main(String args[]) { String[] testCaseName = {TestTypedSet.class.getName()}; junit.textui.TestRunner.main(testCaseName); } //------------------------------------------------------------------- public Set makeEmptySet() { return TypedSet.decorate(new HashSet(), Object.class); } public boolean isNullSupported() { return false; } public boolean skipSerializedCanonicalTests() { return true; // Typed and Predicated get confused } } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootcollections-generic-4.01/src/test/org/apache/commons/collections15/set/TestSynchronizedSortedSet.javacollections-generic-4.01/src/test/org/apache/commons/collections15/set/TestSynchronizedSortedSet.jav0000644000175000017500000000424410464140763034173 0ustar giovannigiovanni/* * Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.set; import junit.framework.Test; import org.apache.commons.collections15.BulkTest; import java.util.Set; import java.util.TreeSet; /** * Extension of {@link AbstractTestSet} for exercising the * {@link SynchronizedSortedSet} implementation. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 19:11:58 $ * @since Commons Collections 3.1 */ public class TestSynchronizedSortedSet extends AbstractTestSortedSet { public TestSynchronizedSortedSet(String testName) { super(testName); } public static Test suite() { return BulkTest.makeSuite(TestSynchronizedSortedSet.class); } public static void main(String args[]) { String[] testCaseName = {TestSynchronizedSortedSet.class.getName()}; junit.textui.TestRunner.main(testCaseName); } //------------------------------------------------------------------- public Set makeEmptySet() { return SynchronizedSortedSet.decorate(new TreeSet()); } public String getCompatibilityVersion() { return "3.1"; } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk((java.io.Serializable) collection, "D:/dev/collections15/data/test/SynchronizedSortedSet.emptyCollection.version3.1.obj"); // resetFull(); // writeExternalFormToDisk((java.io.Serializable) collection, "D:/dev/collections15/data/test/SynchronizedSortedSet.fullCollection.version3.1.obj"); // } } collections-generic-4.01/src/test/org/apache/commons/collections15/set/TestTransformedSet.java0000644000175000017500000000643110464140754032760 0ustar giovannigiovanni/* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.set; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.collections15.collection.TestTransformedCollection; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.Set; /** * Extension of {@link TestSet} for exercising the {@link TransformedSet} * implementation. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 19:11:58 $ * @since Commons Collections 3.0 */ public class TestTransformedSet extends AbstractTestSet { public TestTransformedSet(String testName) { super(testName); } public static Test suite() { return new TestSuite(TestTransformedSet.class); } public static void main(String args[]) { String[] testCaseName = {TestTransformedSet.class.getName()}; junit.textui.TestRunner.main(testCaseName); } public Collection makeConfirmedCollection() { return new HashSet(); } public Collection makeConfirmedFullCollection() { Set set = new HashSet(); set.addAll(Arrays.asList(getFullElements())); return set; } public Set makeEmptySet() { return TransformedSet.decorate(new HashSet(), TestTransformedCollection.NOOP_TRANSFORMER); } public Set makeFullSet() { Set list = new HashSet(); list.addAll(Arrays.asList(getFullElements())); return TransformedSet.decorate(list, TestTransformedCollection.NOOP_TRANSFORMER); } public void testTransformedSet() { Set set = TransformedSet.decorate(new HashSet(), TestTransformedCollection.STRING_TO_INTEGER_TRANSFORMER); assertEquals(0, set.size()); Object[] els = new Object[]{"1", "3", "5", "7", "2", "4", "6"}; for (int i = 0; i < els.length; i++) { set.add(els[i]); assertEquals(i + 1, set.size()); assertEquals(true, set.contains(new Integer((String) els[i]))); assertEquals(false, set.contains(els[i])); } assertEquals(false, set.remove(els[0])); assertEquals(true, set.remove(new Integer((String) els[0]))); } public String getCompatibilityVersion() { return "3.1"; } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk((java.io.Serializable) collection, "D:/dev/collections15/data/test/TransformedSet.emptyCollection.version3.1.obj"); // resetFull(); // writeExternalFormToDisk((java.io.Serializable) collection, "D:/dev/collections15/data/test/TransformedSet.fullCollection.version3.1.obj"); // } } collections-generic-4.01/src/test/org/apache/commons/collections15/set/TestListOrderedSet.java0000644000175000017500000001413610464140760032712 0ustar giovannigiovanni/* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.set; import junit.framework.Test; import junit.framework.TestSuite; import java.util.*; /** * Extension of {@link TestSet} for exercising the {@link ListOrderedSet} * implementation. * * @author Henning P. Schmiedehausen * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 19:11:58 $ * @since Commons Collections 3.0 */ public class TestListOrderedSet extends AbstractTestSet { public TestListOrderedSet(String testName) { super(testName); } public static Test suite() { return new TestSuite(TestListOrderedSet.class); } public static void main(String args[]) { String[] testCaseName = {TestListOrderedSet.class.getName()}; junit.textui.TestRunner.main(testCaseName); } public Set makeEmptySet() { return ListOrderedSet.decorate(new HashSet()); } protected Set setupSet() { Set set = makeEmptySet(); for (int i = 0; i < 10; i++) { set.add(Integer.toString(i)); } return set; } public void testOrdering() { Set set = setupSet(); Iterator it = set.iterator(); for (int i = 0; i < 10; i++) { assertEquals("Sequence is wrong", Integer.toString(i), it.next()); } for (int i = 0; i < 10; i += 2) { assertTrue("Must be able to remove int", set.remove(Integer.toString(i))); } it = set.iterator(); for (int i = 1; i < 10; i += 2) { assertEquals("Sequence is wrong after remove ", Integer.toString(i), it.next()); } for (int i = 0; i < 10; i++) { set.add(Integer.toString(i)); } assertEquals("Size of set is wrong!", 10, set.size()); it = set.iterator(); for (int i = 1; i < 10; i += 2) { assertEquals("Sequence is wrong", Integer.toString(i), it.next()); } for (int i = 0; i < 10; i += 2) { assertEquals("Sequence is wrong", Integer.toString(i), it.next()); } } private static final Integer ZERO = new Integer(0); private static final Integer ONE = new Integer(1); private static final Integer TWO = new Integer(2); private static final Integer THREE = new Integer(3); public void testListAddRemove() { ListOrderedSet set = (ListOrderedSet) makeEmptySet(); List view = set.asList(); set.add(ZERO); set.add(ONE); set.add(TWO); assertEquals(3, set.size()); assertSame(ZERO, set.get(0)); assertSame(ONE, set.get(1)); assertSame(TWO, set.get(2)); assertEquals(3, view.size()); assertSame(ZERO, view.get(0)); assertSame(ONE, view.get(1)); assertSame(TWO, view.get(2)); assertEquals(0, set.indexOf(ZERO)); assertEquals(1, set.indexOf(ONE)); assertEquals(2, set.indexOf(TWO)); set.remove(1); assertEquals(2, set.size()); assertSame(ZERO, set.get(0)); assertSame(TWO, set.get(1)); assertEquals(2, view.size()); assertSame(ZERO, view.get(0)); assertSame(TWO, view.get(1)); } public void testListAddIndexed() { ListOrderedSet set = (ListOrderedSet) makeEmptySet(); List view = set.asList(); set.add(ZERO); set.add(TWO); set.add(1, ONE); assertEquals(3, set.size()); assertSame(ZERO, set.get(0)); assertSame(ONE, set.get(1)); assertSame(TWO, set.get(2)); set.add(0, ONE); assertEquals(3, set.size()); assertSame(ZERO, set.get(0)); assertSame(ONE, set.get(1)); assertSame(TWO, set.get(2)); List list = new ArrayList(); list.add(ZERO); list.add(TWO); set.addAll(0, list); assertEquals(3, set.size()); assertSame(ZERO, set.get(0)); assertSame(ONE, set.get(1)); assertSame(TWO, set.get(2)); list.add(0, THREE); // list = [3,0,2] set.remove(TWO); // set = [0,1] set.addAll(1, list); assertEquals(4, set.size()); assertSame(ZERO, set.get(0)); assertSame(THREE, set.get(1)); assertSame(TWO, set.get(2)); assertSame(ONE, set.get(3)); } public void testDecorator() { try { ListOrderedSet.decorate((List) null); fail(); } catch (IllegalArgumentException ex) { } try { ListOrderedSet.decorate((Set) null); fail(); } catch (IllegalArgumentException ex) { } try { ListOrderedSet.decorate(null, null); fail(); } catch (IllegalArgumentException ex) { } try { ListOrderedSet.decorate(new HashSet(), null); fail(); } catch (IllegalArgumentException ex) { } try { ListOrderedSet.decorate(null, new ArrayList()); fail(); } catch (IllegalArgumentException ex) { } } public String getCompatibilityVersion() { return "3.1"; } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk((java.io.Serializable) collection, "D:/dev/collections15/data/test/ListOrderedSet.emptyCollection.version3.1.obj"); // resetFull(); // writeExternalFormToDisk((java.io.Serializable) collection, "D:/dev/collections15/data/test/ListOrderedSet.fullCollection.version3.1.obj"); // } } collections-generic-4.01/src/test/org/apache/commons/collections15/set/TestTransformedSortedSet.java0000644000175000017500000000630410464140764034141 0ustar giovannigiovanni/* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.set; import junit.framework.Test; import org.apache.commons.collections15.BulkTest; import org.apache.commons.collections15.collection.TestTransformedCollection; import java.util.*; /** * Extension of {@link TestSortedSet} for exercising the {@link TransformedSortedSet} * implementation. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 19:11:58 $ * @since Commons Collections 3.0 */ public class TestTransformedSortedSet extends AbstractTestSortedSet { public TestTransformedSortedSet(String testName) { super(testName); } public static Test suite() { return BulkTest.makeSuite(TestTransformedSortedSet.class); } public static void main(String args[]) { String[] testCaseName = {TestTransformedSortedSet.class.getName()}; junit.textui.TestRunner.main(testCaseName); } //----------------------------------------------------------------------- public Set makeEmptySet() { return TransformedSortedSet.decorate(new TreeSet(), TestTransformedCollection.NOOP_TRANSFORMER); } public Set makeFullSet() { SortedSet set = new TreeSet(); set.addAll(Arrays.asList(getFullElements())); return TransformedSortedSet.decorate(set, TestTransformedCollection.NOOP_TRANSFORMER); } //----------------------------------------------------------------------- public void testTransformedSet() { Set set = TransformedSortedSet.decorate(new HashSet(), TestTransformedCollection.STRING_TO_INTEGER_TRANSFORMER); assertEquals(0, set.size()); Object[] els = new Object[]{"1", "3", "5", "7", "2", "4", "6"}; for (int i = 0; i < els.length; i++) { set.add(els[i]); assertEquals(i + 1, set.size()); assertEquals(true, set.contains(new Integer((String) els[i]))); assertEquals(false, set.contains(els[i])); } assertEquals(false, set.remove(els[0])); assertEquals(true, set.remove(new Integer((String) els[0]))); } public String getCompatibilityVersion() { return "3.1"; } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk((java.io.Serializable) collection, "D:/dev/collections15/data/test/TransformedSortedSet.emptyCollection.version3.1.obj"); // resetFull(); // writeExternalFormToDisk((java.io.Serializable) collection, "D:/dev/collections15/data/test/TransformedSortedSet.fullCollection.version3.1.obj"); // } } collections-generic-4.01/src/test/org/apache/commons/collections15/set/TestSynchronizedSet.java0000644000175000017500000000415610464140765033157 0ustar giovannigiovanni/* * Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.set; import junit.framework.Test; import org.apache.commons.collections15.BulkTest; import java.util.HashSet; import java.util.Set; /** * Extension of {@link AbstractTestSet} for exercising the * {@link SynchronizedSet} implementation. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 19:11:58 $ * @since Commons Collections 3.1 */ public class TestSynchronizedSet extends AbstractTestSet { public TestSynchronizedSet(String testName) { super(testName); } public static Test suite() { return BulkTest.makeSuite(TestSynchronizedSet.class); } public static void main(String args[]) { String[] testCaseName = {TestSynchronizedSet.class.getName()}; junit.textui.TestRunner.main(testCaseName); } //------------------------------------------------------------------- public Set makeEmptySet() { return SynchronizedSet.decorate(new HashSet()); } public String getCompatibilityVersion() { return "3.1"; } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk((java.io.Serializable) collection, "D:/dev/collections15/data/test/SynchronizedSet.emptyCollection.version3.1.obj"); // resetFull(); // writeExternalFormToDisk((java.io.Serializable) collection, "D:/dev/collections15/data/test/SynchronizedSet.fullCollection.version3.1.obj"); // } } collections-generic-4.01/src/test/org/apache/commons/collections15/set/TestAll.java0000644000175000017500000000411310464140765030525 0ustar giovannigiovanni/* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.set; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * Entry point for tests. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 19:11:58 $ * @since Commons Collections 3.0 */ public class TestAll extends TestCase { public TestAll(String testName) { super(testName); } public static void main(String args[]) { String[] testCaseName = {TestAll.class.getName()}; junit.textui.TestRunner.main(testCaseName); } public static Test suite() { TestSuite suite = new TestSuite(); suite.addTest(TestCompositeSet.suite()); suite.addTest(TestListOrderedSet.suite()); suite.addTest(TestListOrderedSet2.suite()); suite.addTest(TestMapBackedSet.suite()); suite.addTest(TestMapBackedSet2.suite()); suite.addTest(TestPredicatedSet.suite()); suite.addTest(TestPredicatedSortedSet.suite()); suite.addTest(TestSynchronizedSet.suite()); suite.addTest(TestSynchronizedSortedSet.suite()); suite.addTest(TestTransformedSet.suite()); suite.addTest(TestTransformedSortedSet.suite()); suite.addTest(TestTypedSet.suite()); suite.addTest(TestTypedSortedSet.suite()); suite.addTest(TestUnmodifiableSet.suite()); suite.addTest(TestUnmodifiableSortedSet.suite()); return suite; } } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootcollections-generic-4.01/src/test/org/apache/commons/collections15/set/TestUnmodifiableSortedSet.javacollections-generic-4.01/src/test/org/apache/commons/collections15/set/TestUnmodifiableSortedSet.jav0000644000175000017500000001104610464140757034113 0ustar giovannigiovanni/* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.set; import junit.framework.Test; import org.apache.commons.collections15.BulkTest; import java.util.*; /** * Extension of {@link AbstractTestSortedSet} for exercising the * {@link UnmodifiableSortedSet} implementation. * * @author Matt Hall, John Watkinson, Phil Steitz * @version $Revision: 1.1 $ $Date: 2005/10/11 19:11:58 $ * @since Commons Collections 3.0 */ public class TestUnmodifiableSortedSet extends AbstractTestSortedSet { public TestUnmodifiableSortedSet(String testName) { super(testName); } public static Test suite() { return BulkTest.makeSuite(TestUnmodifiableSortedSet.class); } public static void main(String args[]) { String[] testCaseName = {TestUnmodifiableSortedSet.class.getName()}; junit.textui.TestRunner.main(testCaseName); } //------------------------------------------------------------------- public Set makeEmptySet() { return UnmodifiableSortedSet.decorate(new TreeSet()); } public Set makeFullSet() { TreeSet set = new TreeSet(); set.addAll(Arrays.asList(getFullElements())); return UnmodifiableSortedSet.decorate(set); } public boolean isAddSupported() { return false; } public boolean isRemoveSupported() { return false; } //-------------------------------------------------------------------- protected UnmodifiableSortedSet set = null; protected ArrayList array = null; protected void setupSet() { set = (UnmodifiableSortedSet) makeFullSet(); array = new ArrayList(); array.add(new Integer(1)); } /** * Verify that base set and subsets are not modifiable */ public void testUnmodifiable() { setupSet(); verifyUnmodifiable(set); verifyUnmodifiable(set.headSet(new Integer(1))); verifyUnmodifiable(set.tailSet(new Integer(1))); verifyUnmodifiable(set.subSet(new Integer(1), new Integer(3))); } /** * Verifies that a set is not modifiable */ public void verifyUnmodifiable(Set set) { try { set.add("value"); fail("Expecting UnsupportedOperationException."); } catch (UnsupportedOperationException e) { // expected } try { set.addAll(new TreeSet()); fail("Expecting UnsupportedOperationException."); } catch (UnsupportedOperationException e) { // expected } try { set.clear(); fail("Expecting UnsupportedOperationException."); } catch (UnsupportedOperationException e) { // expected } try { set.remove("x"); fail("Expecting UnsupportedOperationException."); } catch (UnsupportedOperationException e) { // expected } try { set.removeAll(array); fail("Expecting UnsupportedOperationException."); } catch (UnsupportedOperationException e) { // expected } try { set.retainAll(array); fail("Expecting UnsupportedOperationException."); } catch (UnsupportedOperationException e) { // expected } } public void testComparator() { setupSet(); Comparator c = set.comparator(); assertTrue("natural order, so comparator should be null", c == null); } public String getCompatibilityVersion() { return "3.1"; } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk((java.io.Serializable) collection, "D:/dev/collections15/data/test/UnmodifiableSortedSet.emptyCollection.version3.1.obj"); // resetFull(); // writeExternalFormToDisk((java.io.Serializable) collection, "D:/dev/collections15/data/test/UnmodifiableSortedSet.fullCollection.version3.1.obj"); // } } collections-generic-4.01/src/test/org/apache/commons/collections15/set/TestTypedSortedSet.java0000644000175000017500000000640110464140764032740 0ustar giovannigiovanni/* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.set; import junit.framework.Test; import org.apache.commons.collections15.BulkTest; import java.util.Arrays; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; /** * Extension of {@link AbstractTestSortedSet} for exercising the * {@link TypedSortedSet} implementation. * * @author Matt Hall, John Watkinson, Phil Steitz * @version $Revision: 1.1 $ $Date: 2005/10/11 19:11:58 $ * @since Commons Collections 3.0 */ public class TestTypedSortedSet extends AbstractTestSortedSet { public TestTypedSortedSet(String testName) { super(testName); } public static Test suite() { return BulkTest.makeSuite(TestTypedSortedSet.class); } public static void main(String args[]) { String[] testCaseName = {TestTypedSortedSet.class.getName()}; junit.textui.TestRunner.main(testCaseName); } //------------------------------------------------------------------- protected Class integerType = new Integer(0).getClass(); public Set makeEmptySet() { return TypedSortedSet.decorate(new TreeSet(), integerType); } public Set makeFullSet() { TreeSet set = new TreeSet(); set.addAll(Arrays.asList(getFullElements())); return TypedSortedSet.decorate(set, integerType); } //-------------------------------------------------------------------- protected Long getNextAsLong() { SortedSet set = (SortedSet) makeFullSet(); int nextValue = ((Integer) set.last()).intValue() + 1; return new Long(nextValue); } protected Integer getNextAsInt() { SortedSet set = (SortedSet) makeFullSet(); int nextValue = ((Integer) set.last()).intValue() + 1; return new Integer(nextValue); } public void testIllegalAdd() { Set set = makeFullSet(); try { set.add(getNextAsLong()); fail("Should fail type test."); } catch (IllegalArgumentException e) { // expected } assertTrue("Collection shouldn't convert long to int", !set.contains(getNextAsInt())); } public void testIllegalAddAll() { Set set = makeFullSet(); Set elements = new TreeSet(); elements.add(getNextAsLong()); try { set.addAll(elements); fail("Should fail type test."); } catch (IllegalArgumentException e) { // expected } assertTrue("Collection shouldn't convert long to int", !set.contains(getNextAsInt())); } public boolean skipSerializedCanonicalTests() { return true; // Typed and Predicated get confused } } collections-generic-4.01/src/test/org/apache/commons/collections15/set/TestPredicatedSet.java0000644000175000017500000001013210464140764032532 0ustar giovannigiovanni/* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.set; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.collections15.Predicate; import org.apache.commons.collections15.PredicateUtils; import java.util.HashSet; import java.util.Set; /** * Extension of {@link TestSet} for exercising the * {@link PredicatedSet} implementation. * * @author Matt Hall, John Watkinson, Phil Steitz * @version $Revision: 1.1 $ $Date: 2005/10/11 19:11:58 $ * @since Commons Collections 3.0 */ public class TestPredicatedSet extends AbstractTestSet { public TestPredicatedSet(String testName) { super(testName); } public static Test suite() { return new TestSuite(TestPredicatedSet.class); } public static void main(String args[]) { String[] testCaseName = {TestPredicatedSet.class.getName()}; junit.textui.TestRunner.main(testCaseName); } //------------------------------------------------------------------- protected Predicate truePredicate = PredicateUtils.truePredicate(); protected Set decorateSet(Set set, Predicate predicate) { return PredicatedSet.decorate(set, predicate); } public Set makeEmptySet() { return decorateSet(new HashSet(), truePredicate); } public Object[] getFullElements() { return new Object[]{"1", "3", "5", "7", "2", "4", "6"}; } //-------------------------------------------------------------------- protected Predicate testPredicate = new Predicate() { public boolean evaluate(Object o) { return o instanceof String; } }; protected Set makeTestSet() { return decorateSet(new HashSet(), testPredicate); } public void testGetSet() { Set set = makeTestSet(); assertTrue("returned set should not be null", ((PredicatedSet) set).getSet() != null); } public void testIllegalAdd() { Set set = makeTestSet(); Integer i = new Integer(3); try { set.add(i); fail("Integer should fail string predicate."); } catch (IllegalArgumentException e) { // expected } assertTrue("Collection shouldn't contain illegal element", !set.contains(i)); } public void testIllegalAddAll() { Set set = makeTestSet(); Set elements = new HashSet(); elements.add("one"); elements.add("two"); elements.add(new Integer(3)); elements.add("four"); try { set.addAll(elements); fail("Integer should fail string predicate."); } catch (IllegalArgumentException e) { // expected } assertTrue("Set shouldn't contain illegal element", !set.contains("one")); assertTrue("Set shouldn't contain illegal element", !set.contains("two")); assertTrue("Set shouldn't contain illegal element", !set.contains(new Integer(3))); assertTrue("Set shouldn't contain illegal element", !set.contains("four")); } public String getCompatibilityVersion() { return "3.1"; } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk((java.io.Serializable) collection, "D:/dev/collections15/data/test/PredicatedSet.emptyCollection.version3.1.obj"); // resetFull(); // writeExternalFormToDisk((java.io.Serializable) collection, "D:/dev/collections15/data/test/PredicatedSet.fullCollection.version3.1.obj"); // } }collections-generic-4.01/src/test/org/apache/commons/collections15/set/TestPredicatedSortedSet.java0000644000175000017500000001072010464140765033717 0ustar giovannigiovanni/* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.set; import junit.framework.Test; import org.apache.commons.collections15.BulkTest; import org.apache.commons.collections15.Predicate; import org.apache.commons.collections15.PredicateUtils; import org.apache.commons.collections15.map.TestPredicatedSortedMap; import java.util.*; /** * Extension of {@link AbstractTestSortedSet} for exercising the * {@link PredicatedSortedSet} implementation. * * @author Matt Hall, John Watkinson, Phil Steitz * @version $Revision: 1.1 $ $Date: 2005/10/11 19:11:58 $ * @since Commons Collections 3.0 */ public class TestPredicatedSortedSet extends AbstractTestSortedSet { public TestPredicatedSortedSet(String testName) { super(testName); } public static Test suite() { return BulkTest.makeSuite(TestPredicatedSortedSet.class); } public static void main(String args[]) { String[] testCaseName = {TestPredicatedSortedMap.class.getName()}; junit.textui.TestRunner.main(testCaseName); } //------------------------------------------------------------------- protected Predicate truePredicate = PredicateUtils.truePredicate(); public Set makeEmptySet() { return PredicatedSortedSet.decorate(new TreeSet(), truePredicate); } public Set makeFullSet() { TreeSet set = new TreeSet(); set.addAll(Arrays.asList(getFullElements())); return PredicatedSortedSet.decorate(set, truePredicate); } //-------------------------------------------------------------------- protected Predicate testPredicate = new Predicate() { public boolean evaluate(Object o) { return (o instanceof String) && (((String) o).startsWith("A")); } }; protected SortedSet makeTestSet() { return PredicatedSortedSet.decorate(new TreeSet(), testPredicate); } public void testGetSet() { SortedSet set = makeTestSet(); assertTrue("returned set should not be null", ((PredicatedSortedSet) set).getSet() != null); } public void testIllegalAdd() { SortedSet set = makeTestSet(); String testString = "B"; try { set.add(testString); fail("Should fail string predicate."); } catch (IllegalArgumentException e) { // expected } assertTrue("Collection shouldn't contain illegal element", !set.contains(testString)); } public void testIllegalAddAll() { SortedSet set = makeTestSet(); Set elements = new TreeSet(); elements.add("Aone"); elements.add("Atwo"); elements.add("Bthree"); elements.add("Afour"); try { set.addAll(elements); fail("Should fail string predicate."); } catch (IllegalArgumentException e) { // expected } assertTrue("Set shouldn't contain illegal element", !set.contains("Aone")); assertTrue("Set shouldn't contain illegal element", !set.contains("Atwo")); assertTrue("Set shouldn't contain illegal element", !set.contains("Bthree")); assertTrue("Set shouldn't contain illegal element", !set.contains("Afour")); } public void testComparator() { SortedSet set = makeTestSet(); Comparator c = set.comparator(); assertTrue("natural order, so comparator should be null", c == null); } public String getCompatibilityVersion() { return "3.1"; } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk((java.io.Serializable) collection, "D:/dev/collections15/data/test/PredicatedSortedSet.emptyCollection.version3.1.obj"); // resetFull(); // writeExternalFormToDisk((java.io.Serializable) collection, "D:/dev/collections15/data/test/PredicatedSortedSet.fullCollection.version3.1.obj"); // } } collections-generic-4.01/src/test/org/apache/commons/collections15/set/TestListOrderedSet2.java0000644000175000017500000001263410464140754033000 0ustar giovannigiovanni/* * Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.set; import junit.framework.Test; import junit.framework.TestSuite; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Set; /** * Extension of {@link TestSet} for exercising the {@link ListOrderedSet} * implementation. * * @author Henning P. Schmiedehausen * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 19:11:58 $ * @since Commons Collections 3.1 */ public class TestListOrderedSet2 extends AbstractTestSet { public TestListOrderedSet2(String testName) { super(testName); } public static Test suite() { return new TestSuite(TestListOrderedSet2.class); } public static void main(String args[]) { String[] testCaseName = {TestListOrderedSet2.class.getName()}; junit.textui.TestRunner.main(testCaseName); } public Set makeEmptySet() { return new ListOrderedSet(); } protected Set setupSet() { Set set = makeEmptySet(); for (int i = 0; i < 10; i++) { set.add(Integer.toString(i)); } return set; } public void testOrdering() { Set set = setupSet(); Iterator it = set.iterator(); for (int i = 0; i < 10; i++) { assertEquals("Sequence is wrong", Integer.toString(i), it.next()); } for (int i = 0; i < 10; i += 2) { assertTrue("Must be able to remove int", set.remove(Integer.toString(i))); } it = set.iterator(); for (int i = 1; i < 10; i += 2) { assertEquals("Sequence is wrong after remove ", Integer.toString(i), it.next()); } for (int i = 0; i < 10; i++) { set.add(Integer.toString(i)); } assertEquals("Size of set is wrong!", 10, set.size()); it = set.iterator(); for (int i = 1; i < 10; i += 2) { assertEquals("Sequence is wrong", Integer.toString(i), it.next()); } for (int i = 0; i < 10; i += 2) { assertEquals("Sequence is wrong", Integer.toString(i), it.next()); } } private static final Integer ZERO = new Integer(0); private static final Integer ONE = new Integer(1); private static final Integer TWO = new Integer(2); private static final Integer THREE = new Integer(3); public void testListAddRemove() { ListOrderedSet set = (ListOrderedSet) makeEmptySet(); List view = set.asList(); set.add(ZERO); set.add(ONE); set.add(TWO); assertEquals(3, set.size()); assertSame(ZERO, set.get(0)); assertSame(ONE, set.get(1)); assertSame(TWO, set.get(2)); assertEquals(3, view.size()); assertSame(ZERO, view.get(0)); assertSame(ONE, view.get(1)); assertSame(TWO, view.get(2)); assertEquals(0, set.indexOf(ZERO)); assertEquals(1, set.indexOf(ONE)); assertEquals(2, set.indexOf(TWO)); set.remove(1); assertEquals(2, set.size()); assertSame(ZERO, set.get(0)); assertSame(TWO, set.get(1)); assertEquals(2, view.size()); assertSame(ZERO, view.get(0)); assertSame(TWO, view.get(1)); } public void testListAddIndexed() { ListOrderedSet set = (ListOrderedSet) makeEmptySet(); List view = set.asList(); set.add(ZERO); set.add(TWO); set.add(1, ONE); assertEquals(3, set.size()); assertSame(ZERO, set.get(0)); assertSame(ONE, set.get(1)); assertSame(TWO, set.get(2)); set.add(0, ONE); assertEquals(3, set.size()); assertSame(ZERO, set.get(0)); assertSame(ONE, set.get(1)); assertSame(TWO, set.get(2)); List list = new ArrayList(); list.add(ZERO); list.add(TWO); set.addAll(0, list); assertEquals(3, set.size()); assertSame(ZERO, set.get(0)); assertSame(ONE, set.get(1)); assertSame(TWO, set.get(2)); list.add(0, THREE); // list = [3,0,2] set.remove(TWO); // set = [0,1] set.addAll(1, list); assertEquals(4, set.size()); assertSame(ZERO, set.get(0)); assertSame(THREE, set.get(1)); assertSame(TWO, set.get(2)); assertSame(ONE, set.get(3)); } public String getCompatibilityVersion() { return "3.1"; } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk((java.io.Serializable) collection, "D:/dev/collections15/data/test/ListOrderedSet.emptyCollection.version3.1.obj"); // resetFull(); // writeExternalFormToDisk((java.io.Serializable) collection, "D:/dev/collections15/data/test/ListOrderedSet.fullCollection.version3.1.obj"); // } } collections-generic-4.01/src/test/org/apache/commons/collections15/TestFastArrayList1.java0000644000175000017500000000355610464140760032040 0ustar giovannigiovanni/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15; import junit.framework.Test; import java.util.ArrayList; import java.util.List; import org.apache.commons.collections15.list.FastArrayList; /** * Test FastArrayList implementation in fast mode. * * @author Matt Hall, John Watkinson, Jason van Zyl * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:39 $ */ public class TestFastArrayList1 extends TestFastArrayList { public TestFastArrayList1(String testName) { super(testName); } public static Test suite() { return BulkTest.makeSuite(TestFastArrayList1.class); } public static void main(String args[]) { String[] testCaseName = {TestFastArrayList1.class.getName()}; junit.textui.TestRunner.main(testCaseName); } public void setUp() { list = (ArrayList) makeEmptyList(); } public List makeEmptyList() { FastArrayList fal = new FastArrayList(); fal.setFast(true); return (fal); } public String[] ignoredTests() { // subList impl result in... return new String[]{"TestFastArrayList1.bulkTestSubList.bulkTestListIterator.testAddThenSet", "TestFastArrayList1.bulkTestSubList.bulkTestListIterator.testAddThenRemove", }; } } collections-generic-4.01/src/test/org/apache/commons/collections15/TestFastArrayList.java0000644000175000017500000000306310464140762031752 0ustar giovannigiovanni/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15; import junit.framework.Test; import java.util.ArrayList; import java.util.List; import org.apache.commons.collections15.list.FastArrayList; /** * Test FastArrayList. * * @author Matt Hall, John Watkinson, Jason van Zyl * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:39 $ */ public class TestFastArrayList extends TestArrayList { public TestFastArrayList(String testName) { super(testName); } public static Test suite() { return BulkTest.makeSuite(TestFastArrayList.class); } public static void main(String args[]) { String[] testCaseName = {TestFastArrayList.class.getName()}; junit.textui.TestRunner.main(testCaseName); } public void setUp() { list = (ArrayList) makeEmptyList(); } public List makeEmptyList() { FastArrayList fal = new FastArrayList(); fal.setFast(false); return (fal); } } collections-generic-4.01/src/test/org/apache/commons/collections15/TestArrayStack.java0000644000175000017500000000664110464140765031276 0ustar giovannigiovanni/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15; import junit.framework.Test; import java.util.EmptyStackException; import java.util.List; /** * Tests ArrayStack. * * @author Matt Hall, John Watkinson, Craig McClanahan * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:39 $ */ public class TestArrayStack extends TestArrayList { protected ArrayStack stack = null; public TestArrayStack(String testName) { super(testName); } public static Test suite() { return BulkTest.makeSuite(TestArrayStack.class); } public static void main(String args[]) { String[] testCaseName = {TestArrayStack.class.getName()}; junit.textui.TestRunner.main(testCaseName); } public List makeEmptyList() { return new ArrayStack(); } public void setUp() { stack = (ArrayStack) makeEmptyList(); list = stack; } //----------------------------------------------------------------------- public void testNewStack() { assertTrue("New stack is empty", stack.empty()); assertEquals("New stack has size zero", stack.size(), 0); try { stack.peek(); fail("peek() should have thrown EmptyStackException"); } catch (EmptyStackException e) { ; // Expected result } try { stack.pop(); fail("pop() should have thrown EmptyStackException"); } catch (EmptyStackException e) { ; // Expected result } } public void testPushPeekPop() { stack.push("First Item"); assertTrue("Stack is not empty", !stack.empty()); assertEquals("Stack size is one", stack.size(), 1); assertEquals("Top item is 'First Item'", (String) stack.peek(), "First Item"); assertEquals("Stack size is one", stack.size(), 1); stack.push("Second Item"); assertEquals("Stack size is two", stack.size(), 2); assertEquals("Top item is 'Second Item'", (String) stack.peek(), "Second Item"); assertEquals("Stack size is two", stack.size(), 2); assertEquals("Popped item is 'Second Item'", (String) stack.pop(), "Second Item"); assertEquals("Top item is 'First Item'", (String) stack.peek(), "First Item"); assertEquals("Stack size is one", stack.size(), 1); assertEquals("Popped item is 'First Item'", (String) stack.pop(), "First Item"); assertEquals("Stack size is zero", stack.size(), 0); } public void testSearch() { stack.push("First Item"); stack.push("Second Item"); assertEquals("Top item is 'Second Item'", stack.search("Second Item"), 1); assertEquals("Next Item is 'First Item'", stack.search("First Item"), 2); assertEquals("Cannot find 'Missing Item'", stack.search("Missing Item"), -1); } } collections-generic-4.01/src/test/org/apache/commons/collections15/comparators/0000755000175000017500000000000011664401370030045 5ustar giovannigiovanni././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootcollections-generic-4.01/src/test/org/apache/commons/collections15/comparators/TestReverseComparator.javacollections-generic-4.01/src/test/org/apache/commons/collections15/comparators/TestReverseComparator0000644000175000017500000000567410464140762034311 0ustar giovannigiovanni/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.comparators; import junit.framework.Test; import junit.framework.TestSuite; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Collections; import java.util.Comparator; import java.util.LinkedList; import java.util.List; /** * Tests for ReverseComparator. * * @author Matt Hall, John Watkinson, Unknown * @version $Revision: 1.1 $ $Date: 2005/10/11 19:11:58 $ */ public class TestReverseComparator extends AbstractTestComparator { public TestReverseComparator(String testName) { super(testName); } public static Test suite() { return new TestSuite(TestReverseComparator.class); } /** * For the purposes of this test, return a * ReverseComparator that wraps the java.util.Collections.reverseOrder() * Comparator. The resulting comparator should * sort according to natural Order. (Note: we wrap * a Comparator taken from the JDK so that we can * save a "canonical" form in CVS. * * @return Comparator that returns "natural" order */ public Comparator makeComparator() { return new ReverseComparator(Collections.reverseOrder()); } public List getComparableObjectsOrdered() { List list = new LinkedList(); list.add(new Integer(1)); list.add(new Integer(2)); list.add(new Integer(3)); list.add(new Integer(4)); list.add(new Integer(5)); return list; } /** * Override this inherited test since Collections.reverseOrder * doesn't adhere to the "soft" Comparator contract, and we've * already "cannonized" the comparator returned by makeComparator. */ public void testSerializeDeserializeThenCompare() throws Exception { Comparator comp = new ReverseComparator(new ComparableComparator()); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(buffer); out.writeObject(comp); out.close(); ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(buffer.toByteArray())); Object dest = in.readObject(); in.close(); assertEquals("obj != deserialize(serialize(obj))", comp, dest); } } ././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootcollections-generic-4.01/src/test/org/apache/commons/collections15/comparators/AbstractTestComparator.javacollections-generic-4.01/src/test/org/apache/commons/collections15/comparators/AbstractTestComparato0000644000175000017500000001571310464140756034255 0ustar giovannigiovanni/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.comparators; import org.apache.commons.collections15.AbstractTestObject; import java.io.FileNotFoundException; import java.io.IOException; import java.io.Serializable; import java.util.Collections; import java.util.Comparator; import java.util.LinkedList; import java.util.List; /** * Abstract test class for testing the Comparator interface. *

                  * Concrete subclasses declare the comparator to be tested. * They also declare certain aspects of the tests. * * @author Matt Hall, John Watkinson, Stephen Colebourne */ public abstract class AbstractTestComparator extends AbstractTestObject { /** * JUnit constructor. * * @param testName the test class name */ public AbstractTestComparator(String testName) { super(testName); } //----------------------------------------------------------------------- /** * Implement this method to return the comparator to test. * * @return the comparator to test */ public abstract Comparator makeComparator(); /** * Implement this method to return a list of sorted objects. * * @return sorted objects */ public abstract List getComparableObjectsOrdered(); //----------------------------------------------------------------------- /** * Implements the abstract superclass method to return the comparator. * * @return a full iterator */ public Object makeObject() { return makeComparator(); } /** * Overrides superclass to block tests. */ public boolean supportsEmptyCollections() { return false; } /** * Overrides superclass to block tests. */ public boolean supportsFullCollections() { return false; } /** * Overrides superclass to set the compatability to version 2 * as there were no Comparators in version 1.x. */ public String getCompatibilityVersion() { return "2"; } //----------------------------------------------------------------------- /** * Reverse the list. */ protected void reverseObjects(List list) { Collections.reverse(list); } /** * Randomize the list. */ protected void randomizeObjects(List list) { Collections.shuffle(list); } /** * Sort the list. */ protected void sortObjects(List list, Comparator comparator) { Collections.sort(list, comparator); } //----------------------------------------------------------------------- /** * Test sorting an empty list */ public void testEmptyListSort() { List list = new LinkedList(); sortObjects(list, makeComparator()); List list2 = new LinkedList(); assertTrue("Comparator cannot sort empty lists", list2.equals(list)); } /** * Test sorting a reversed list. */ public void testReverseListSort() { Comparator comparator = makeComparator(); List randomList = getComparableObjectsOrdered(); reverseObjects(randomList); sortObjects(randomList, comparator); List orderedList = getComparableObjectsOrdered(); assertTrue("Comparator did not reorder the List correctly", orderedList.equals(randomList)); } /** * Test sorting a random list. */ public void testRandomListSort() { Comparator comparator = makeComparator(); List randomList = getComparableObjectsOrdered(); randomizeObjects(randomList); sortObjects(randomList, comparator); List orderedList = getComparableObjectsOrdered(); /* debug Iterator i = randomList.iterator(); while (i.hasNext()) { System.out.println(i.next()); } */ assertTrue("Comparator did not reorder the List correctly", orderedList.equals(randomList)); } /** * Nearly all Comparators should be Serializable. */ public void testComparatorIsSerializable() { Comparator comparator = makeComparator(); assertTrue("This comparator should be Serializable.", comparator instanceof Serializable); } public String getCanonicalComparatorName(Object object) { StringBuffer retval = new StringBuffer(); retval.append("data/test/"); String colName = object.getClass().getName(); colName = colName.substring(colName.lastIndexOf(".") + 1, colName.length()); retval.append(colName); retval.append(".version"); retval.append(getCompatibilityVersion()); retval.append(".obj"); return retval.toString(); } /** * Compare the current serialized form of the Comparator * against the canonical version in CVS. */ public void testComparatorCompatibility() throws IOException, ClassNotFoundException { if (!skipSerializedCanonicalTests()) { // Disabled as binary compatibility with 3.0 is not supported. // Comparator comparator = null; // // // test to make sure the canonical form has been preserved // try { // comparator = (Comparator) readExternalFormFromDisk(getCanonicalComparatorName(makeComparator())); // } catch (FileNotFoundException exception) { // // boolean autoCreateSerialized = false; // // if (autoCreateSerialized) { // comparator = makeComparator(); // String fileName = getCanonicalComparatorName(comparator); // writeExternalFormToDisk((Serializable) comparator, fileName); // fail("Serialized form could not be found. A serialized version " + "has now been written (and should be added to CVS): " + fileName); // } else { // fail("The Serialized form could be located to test serialization " + "compatibility: " + exception.getMessage()); // } // } // // // // make sure the canonical form produces the ordering we currently // // expect // List randomList = getComparableObjectsOrdered(); // reverseObjects(randomList); // sortObjects(randomList, comparator); // // List orderedList = getComparableObjectsOrdered(); // // assertTrue("Comparator did not reorder the List correctly", orderedList.equals(randomList)); } } } ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootcollections-generic-4.01/src/test/org/apache/commons/collections15/comparators/TestComparatorChain.javacollections-generic-4.01/src/test/org/apache/commons/collections15/comparators/TestComparatorChain.j0000644000175000017500000001507410464140764034145 0ustar giovannigiovanni/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.comparators; import junit.framework.Test; import junit.framework.TestSuite; import java.io.Serializable; import java.util.Comparator; import java.util.LinkedList; import java.util.List; /** * Tests for ComparatorChain. * * @author Matt Hall, John Watkinson, Unknown * @version $Revision: 1.1 $ $Date: 2005/10/11 19:11:58 $ */ public class TestComparatorChain extends AbstractTestComparator { public TestComparatorChain(String testName) { super(testName); } public static Test suite() { return new TestSuite(TestComparatorChain.class); } public Comparator makeComparator() { ComparatorChain chain = new ComparatorChain(new ColumnComparator(0)); chain.addComparator(new ColumnComparator(1), true); // reverse the second column chain.addComparator(new ColumnComparator(2), false); return chain; } public void testNoopComparatorChain() { ComparatorChain chain = new ComparatorChain(); Integer i1 = new Integer(4); Integer i2 = new Integer(6); chain.addComparator(new ComparableComparator()); int correctValue = i1.compareTo(i2); assertTrue("Comparison returns the right order", chain.compare(i1, i2) == correctValue); } public void testBadNoopComparatorChain() { ComparatorChain chain = new ComparatorChain(); Integer i1 = new Integer(4); Integer i2 = new Integer(6); try { chain.compare(i1, i2); fail("An exception should be thrown when a chain contains zero comparators."); } catch (UnsupportedOperationException e) { } } public void testListComparatorChain() { List list = new LinkedList(); list.add(new ComparableComparator()); ComparatorChain chain = new ComparatorChain(list); Integer i1 = new Integer(4); Integer i2 = new Integer(6); int correctValue = i1.compareTo(i2); assertTrue("Comparison returns the right order", chain.compare(i1, i2) == correctValue); } public void testBadListComparatorChain() { List list = new LinkedList(); ComparatorChain chain = new ComparatorChain(list); Integer i1 = new Integer(4); Integer i2 = new Integer(6); try { chain.compare(i1, i2); fail("An exception should be thrown when a chain contains zero comparators."); } catch (UnsupportedOperationException e) { } } public void testComparatorChainOnMinvaluedCompatator() { // -1 * Integer.MIN_VALUE is less than 0, // test that ComparatorChain handles this edge case correctly ComparatorChain chain = new ComparatorChain(); chain.addComparator(new Comparator() { public int compare(Object a, Object b) { int result = ((Comparable) a).compareTo(b); if (result < 0) { return Integer.MIN_VALUE; } else if (result > 0) { return Integer.MAX_VALUE; } else { return 0; } } }, true); assertTrue(chain.compare(new Integer(4), new Integer(5)) > 0); assertTrue(chain.compare(new Integer(5), new Integer(4)) < 0); assertTrue(chain.compare(new Integer(4), new Integer(4)) == 0); } public List getComparableObjectsOrdered() { List list = new LinkedList(); // this is the correct order assuming a // "0th forward, 1st reverse, 2nd forward" sort list.add(new PseudoRow(1, 2, 3)); list.add(new PseudoRow(2, 3, 5)); list.add(new PseudoRow(2, 2, 4)); list.add(new PseudoRow(2, 2, 8)); list.add(new PseudoRow(3, 1, 0)); list.add(new PseudoRow(4, 4, 4)); list.add(new PseudoRow(4, 4, 7)); return list; } public static class PseudoRow implements Serializable { public int cols[] = new int[3]; public PseudoRow(int col1, int col2, int col3) { cols[0] = col1; cols[1] = col2; cols[2] = col3; } public int getColumn(int colIndex) { return cols[colIndex]; } public String toString() { StringBuffer buf = new StringBuffer(); buf.append("["); buf.append(cols[0]); buf.append(","); buf.append(cols[1]); buf.append(","); buf.append(cols[2]); buf.append("]"); return buf.toString(); } public boolean equals(Object o) { if (!(o instanceof PseudoRow)) { return false; } PseudoRow row = (PseudoRow) o; if (getColumn(0) != row.getColumn(0)) { return false; } if (getColumn(1) != row.getColumn(1)) { return false; } if (getColumn(2) != row.getColumn(2)) { return false; } return true; } } public static class ColumnComparator implements Comparator, Serializable { protected int colIndex = 0; public ColumnComparator(int colIndex) { this.colIndex = colIndex; } public int compare(Object o1, Object o2) { int col1 = ((PseudoRow) o1).getColumn(colIndex); int col2 = ((PseudoRow) o2).getColumn(colIndex); if (col1 > col2) { return 1; } else if (col1 < col2) { return -1; } return 0; } public int hashCode() { return colIndex; } public boolean equals(Object that) { if (that instanceof ColumnComparator) { return colIndex == ((ColumnComparator) that).colIndex; } else { return false; } } private static final long serialVersionUID = -2284880866328872105L; } } ././@LongLink0000000000000000000000000000015500000000000011566 Lustar rootrootcollections-generic-4.01/src/test/org/apache/commons/collections15/comparators/TestFixedOrderComparator.javacollections-generic-4.01/src/test/org/apache/commons/collections15/comparators/TestFixedOrderCompara0000644000175000017500000001713510464140764034201 0ustar giovannigiovanni/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.comparators; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import java.util.*; /** * Test class for FixedOrderComparator. * * @author David Leppik * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 19:11:58 $ */ public class TestFixedOrderComparator extends TestCase { /** * Top cities of the world, by population including metro areas. */ public static final String topCities[] = new String[]{"Tokyo", "Mexico City", "Mumbai", "Sao Paulo", "New York", "Shanghai", "Lagos", "Los Angeles", "Calcutta", "Buenos Aires"}; // // Initialization and busywork // public TestFixedOrderComparator(String name) { super(name); } public static Test suite() { return new TestSuite(TestFixedOrderComparator.class); } public static void main(String args[]) { junit.textui.TestRunner.run(suite()); } // // Set up and tear down // // // The tests // /** * Tests that the constructor plus add method compares items properly. */ public void testConstructorPlusAdd() { FixedOrderComparator comparator = new FixedOrderComparator(); for (int i = 0; i < topCities.length; i++) { comparator.add(topCities[i]); } String[] keys = (String[]) topCities.clone(); assertComparatorYieldsOrder(keys, comparator); } /** * Tests that the array constructor compares items properly. */ public void testArrayConstructor() { String[] keys = (String[]) topCities.clone(); String[] topCitiesForTest = (String[]) topCities.clone(); FixedOrderComparator comparator = new FixedOrderComparator(topCitiesForTest); assertComparatorYieldsOrder(keys, comparator); // test that changing input after constructor has no effect topCitiesForTest[0] = "Brighton"; assertComparatorYieldsOrder(keys, comparator); } /** * Tests the list constructor. */ public void testListConstructor() { String[] keys = (String[]) topCities.clone(); List topCitiesForTest = new LinkedList(Arrays.asList(topCities)); FixedOrderComparator comparator = new FixedOrderComparator(topCitiesForTest); assertComparatorYieldsOrder(keys, comparator); // test that changing input after constructor has no effect topCitiesForTest.set(0, "Brighton"); assertComparatorYieldsOrder(keys, comparator); } /** * Tests addAsEqual method. */ public void testAddAsEqual() { FixedOrderComparator comparator = new FixedOrderComparator(topCities); comparator.addAsEqual("New York", "Minneapolis"); assertEquals(0, comparator.compare("New York", "Minneapolis")); assertEquals(-1, comparator.compare("Tokyo", "Minneapolis")); assertEquals(1, comparator.compare("Shanghai", "Minneapolis")); } /** * Tests whether or not updates are disabled after a comparison is made. */ public void testLock() { FixedOrderComparator comparator = new FixedOrderComparator(topCities); assertEquals(false, comparator.isLocked()); comparator.compare("New York", "Tokyo"); assertEquals(true, comparator.isLocked()); try { comparator.add("Minneapolis"); fail("Should have thrown an UnsupportedOperationException"); } catch (UnsupportedOperationException e) { // success -- ignore } try { comparator.addAsEqual("New York", "Minneapolis"); fail("Should have thrown an UnsupportedOperationException"); } catch (UnsupportedOperationException e) { // success -- ignore } } public void testUnknownObjectBehavior() { FixedOrderComparator comparator = new FixedOrderComparator(topCities); try { comparator.compare("New York", "Minneapolis"); fail("Should have thrown a IllegalArgumentException"); } catch (IllegalArgumentException e) { // success-- ignore } try { comparator.compare("Minneapolis", "New York"); fail("Should have thrown a IllegalArgumentException"); } catch (IllegalArgumentException e) { // success-- ignore } assertEquals(FixedOrderComparator.UNKNOWN_THROW_EXCEPTION, comparator.getUnknownObjectBehavior()); comparator = new FixedOrderComparator(topCities); comparator.setUnknownObjectBehavior(FixedOrderComparator.UNKNOWN_BEFORE); assertEquals(FixedOrderComparator.UNKNOWN_BEFORE, comparator.getUnknownObjectBehavior()); LinkedList keys = new LinkedList(Arrays.asList(topCities)); keys.addFirst("Minneapolis"); assertComparatorYieldsOrder(keys.toArray(new String[0]), comparator); assertEquals(-1, comparator.compare("Minneapolis", "New York")); assertEquals(1, comparator.compare("New York", "Minneapolis")); assertEquals(0, comparator.compare("Minneapolis", "St Paul")); comparator = new FixedOrderComparator(topCities); comparator.setUnknownObjectBehavior(FixedOrderComparator.UNKNOWN_AFTER); keys = new LinkedList(Arrays.asList(topCities)); keys.add("Minneapolis"); assertComparatorYieldsOrder(keys.toArray(new String[0]), comparator); assertEquals(1, comparator.compare("Minneapolis", "New York")); assertEquals(-1, comparator.compare("New York", "Minneapolis")); assertEquals(0, comparator.compare("Minneapolis", "St Paul")); } // // Helper methods // /** * Shuffles the keys and asserts that the comparator sorts them back to * their original order. */ private void assertComparatorYieldsOrder(Object[] orderedObjects, Comparator comparator) { Object[] keys = (Object[]) orderedObjects.clone(); // shuffle until the order changes. It's extremely rare that // this requires more than one shuffle. boolean isInNewOrder = false; while (keys.length > 1 && isInNewOrder == false) { shuffle: { Random rand = new Random(); for (int i = keys.length - 1; i > 0; i--) { Object swap = keys[i]; int j = rand.nextInt(i + 1); keys[i] = keys[j]; keys[j] = swap; } } testShuffle: { for (int i = 0; i < keys.length && !isInNewOrder; i++) { if (!orderedObjects[i].equals(keys[i])) { isInNewOrder = true; } } } } // The real test: sort and make sure they come out right. Arrays.sort(keys, comparator); for (int i = 0; i < orderedObjects.length; i++) { assertEquals(orderedObjects[i], keys[i]); } } } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootcollections-generic-4.01/src/test/org/apache/commons/collections15/comparators/TestNullComparator.javacollections-generic-4.01/src/test/org/apache/commons/collections15/comparators/TestNullComparator.ja0000644000175000017500000000617310464140761034173 0ustar giovannigiovanni/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.comparators; import junit.framework.Test; import junit.framework.TestSuite; import java.util.Comparator; import java.util.LinkedList; import java.util.List; /** * Test the NullComparator. * * @author Matt Hall, John Watkinson, Michael A. Smith * @version $Revision: 1.1 $ $Date: 2005/10/11 19:11:58 $ */ public abstract class TestNullComparator extends AbstractTestComparator { public TestNullComparator(String testName) { super(testName); } public static Test suite() { TestSuite suite = new TestSuite(TestNullComparator.class.getName()); suite.addTest(new TestSuite(TestNullComparator1.class)); suite.addTest(new TestSuite(TestNullComparator2.class)); return suite; } /** * Test the NullComparator with nulls high, using comparable comparator */ public static class TestNullComparator1 extends TestNullComparator { public TestNullComparator1(String testName) { super(testName); } public Comparator makeComparator() { return new NullComparator(ComparableComparator.getInstance()); } public List getComparableObjectsOrdered() { List list = new LinkedList(); list.add(new Integer(1)); list.add(new Integer(2)); list.add(new Integer(3)); list.add(new Integer(4)); list.add(new Integer(5)); list.add(null); return list; } public String getCanonicalComparatorName(Object object) { return super.getCanonicalComparatorName(object) + "1"; } } /** * Test the NullComparator with nulls low using the comparable comparator */ public static class TestNullComparator2 extends TestNullComparator { public TestNullComparator2(String testName) { super(testName); } public Comparator makeComparator() { return new NullComparator(ComparableComparator.getInstance(), false); } public List getComparableObjectsOrdered() { List list = new LinkedList(); list.add(null); list.add(new Integer(1)); list.add(new Integer(2)); list.add(new Integer(3)); list.add(new Integer(4)); list.add(new Integer(5)); return list; } public String getCanonicalComparatorName(Object object) { return super.getCanonicalComparatorName(object) + "2"; } } } collections-generic-4.01/src/test/org/apache/commons/collections15/comparators/TestAll.java0000644000175000017500000000320210464140755032261 0ustar giovannigiovanni/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.comparators; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * Entry point for all Comparator Collections tests. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 19:11:58 $ */ public class TestAll extends TestCase { public TestAll(String testName) { super(testName); } public static Test suite() { TestSuite suite = new TestSuite(); suite.addTest(TestBooleanComparator.suite()); suite.addTest(TestComparableComparator.suite()); suite.addTest(TestComparatorChain.suite()); suite.addTest(TestFixedOrderComparator.suite()); suite.addTest(TestNullComparator.suite()); suite.addTest(TestReverseComparator.suite()); return suite; } public static void main(String args[]) { String[] testCaseName = {TestAll.class.getName()}; junit.textui.TestRunner.main(testCaseName); } } ././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootcollections-generic-4.01/src/test/org/apache/commons/collections15/comparators/TestBooleanComparator.javacollections-generic-4.01/src/test/org/apache/commons/collections15/comparators/TestBooleanComparator0000644000175000017500000001433310464140763034246 0ustar giovannigiovanni/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.comparators; import junit.framework.Test; import junit.framework.TestSuite; import java.util.ArrayList; import java.util.Comparator; import java.util.List; /** * Tests for {@link BooleanComparator}. * * @author Matt Hall, John Watkinson, Rodney Waldhoff * @version $Revision: 1.1 $ $Date: 2005/10/11 19:11:58 $ */ public class TestBooleanComparator extends AbstractTestComparator { // conventional // ------------------------------------------------------------------------ public TestBooleanComparator(String testName) { super(testName); } public static Test suite() { return new TestSuite(TestBooleanComparator.class); } // collections15 testing framework // ------------------------------------------------------------------------ public Comparator makeComparator() { return new BooleanComparator(); } public List getComparableObjectsOrdered() { List list = new ArrayList(); list.add(new Boolean(false)); list.add(Boolean.FALSE); list.add(new Boolean(false)); list.add(Boolean.TRUE); list.add(new Boolean(true)); list.add(Boolean.TRUE); return list; } public String getCompatibilityVersion() { return "3"; } // tests // ------------------------------------------------------------------------ public void testConstructors() { allTests(false, new BooleanComparator()); allTests(false, new BooleanComparator(false)); allTests(true, new BooleanComparator(true)); } public void testStaticFactoryMethods() { allTests(false, BooleanComparator.getFalseFirstComparator()); allTests(false, BooleanComparator.getBooleanComparator(false)); allTests(true, BooleanComparator.getTrueFirstComparator()); allTests(true, BooleanComparator.getBooleanComparator(true)); } public void testEqualsCompatibleInstance() { assertEquals(new BooleanComparator(), new BooleanComparator(false)); assertEquals(new BooleanComparator(false), new BooleanComparator(false)); assertEquals(new BooleanComparator(false), BooleanComparator.getFalseFirstComparator()); assertSame(BooleanComparator.getFalseFirstComparator(), BooleanComparator.getBooleanComparator(false)); assertEquals(new BooleanComparator(true), new BooleanComparator(true)); assertEquals(new BooleanComparator(true), BooleanComparator.getTrueFirstComparator()); assertSame(BooleanComparator.getTrueFirstComparator(), BooleanComparator.getBooleanComparator(true)); assertTrue(!(new BooleanComparator().equals(new BooleanComparator(true)))); assertTrue(!(new BooleanComparator(true).equals(new BooleanComparator(false)))); } // utilities // ------------------------------------------------------------------------ protected void allTests(boolean trueFirst, BooleanComparator comp) { orderIndependentTests(comp); if (trueFirst) { trueFirstTests(comp); } else { falseFirstTests(comp); } } protected void trueFirstTests(BooleanComparator comp) { assertNotNull(comp); assertEquals(0, comp.compare(Boolean.TRUE, Boolean.TRUE)); assertEquals(0, comp.compare(Boolean.FALSE, Boolean.FALSE)); assertTrue(comp.compare(Boolean.FALSE, Boolean.TRUE) > 0); assertTrue(comp.compare(Boolean.TRUE, Boolean.FALSE) < 0); assertEquals(0, comp.compare(Boolean.TRUE, Boolean.TRUE)); assertEquals(0, comp.compare(Boolean.FALSE, Boolean.FALSE)); assertTrue(comp.compare(Boolean.FALSE, Boolean.TRUE) > 0); assertTrue(comp.compare(Boolean.TRUE, Boolean.FALSE) < 0); } protected void falseFirstTests(BooleanComparator comp) { assertNotNull(comp); assertEquals(0, comp.compare(Boolean.TRUE, Boolean.TRUE)); assertEquals(0, comp.compare(Boolean.FALSE, Boolean.FALSE)); assertTrue(comp.compare(Boolean.FALSE, Boolean.TRUE) < 0); assertTrue(comp.compare(Boolean.TRUE, Boolean.FALSE) > 0); assertEquals(0, comp.compare(Boolean.TRUE, Boolean.TRUE)); assertEquals(0, comp.compare(Boolean.FALSE, Boolean.FALSE)); assertTrue(comp.compare(Boolean.FALSE, Boolean.TRUE) < 0); assertTrue(comp.compare(Boolean.TRUE, Boolean.FALSE) > 0); } protected void orderIndependentTests(BooleanComparator comp) { nullArgumentTests(comp); nonBooleanArgumentTests(comp); } protected void nullArgumentTests(BooleanComparator comp) { assertNotNull(comp); try { comp.compare(null, null); fail("Expected NullPointerException"); } catch (NullPointerException e) { // expected } try { comp.compare(Boolean.TRUE, null); fail("Expected NullPointerException"); } catch (NullPointerException e) { // expected } try { comp.compare(Boolean.FALSE, null); fail("Expected NullPointerException"); } catch (NullPointerException e) { // expected } try { comp.compare(null, Boolean.TRUE); fail("Expected NullPointerException"); } catch (NullPointerException e) { // expected } try { comp.compare(null, Boolean.FALSE); fail("Expected NullPointerException"); } catch (NullPointerException e) { // expected } } protected void nonBooleanArgumentTests(BooleanComparator comp) { assertNotNull(comp); } } ././@LongLink0000000000000000000000000000015500000000000011566 Lustar rootrootcollections-generic-4.01/src/test/org/apache/commons/collections15/comparators/TestComparableComparator.javacollections-generic-4.01/src/test/org/apache/commons/collections15/comparators/TestComparableCompara0000644000175000017500000000312210464140760034176 0ustar giovannigiovanni/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.comparators; import junit.framework.Test; import junit.framework.TestSuite; import java.util.Comparator; import java.util.LinkedList; import java.util.List; /** * Tests for ComparableComparator. * * @author Matt Hall, John Watkinson, Unknown * @version $Revision: 1.1 $ $Date: 2005/10/11 19:11:58 $ */ public class TestComparableComparator extends AbstractTestComparator { public TestComparableComparator(String testName) { super(testName); } public static Test suite() { return new TestSuite(TestComparableComparator.class); } public Comparator makeComparator() { return new ComparableComparator(); } public List getComparableObjectsOrdered() { List list = new LinkedList(); list.add(new Integer(1)); list.add(new Integer(2)); list.add(new Integer(3)); list.add(new Integer(4)); list.add(new Integer(5)); return list; } } collections-generic-4.01/src/test/org/apache/commons/collections15/TestFactoryUtils.java0000644000175000017500000002262610464140757031664 0ustar giovannigiovanni/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15; import junit.framework.Test; import junit.framework.TestSuite; import junit.textui.TestRunner; import org.apache.commons.collections15.functors.ConstantFactory; import java.io.*; import java.util.Date; import java.util.TimeZone; /** * Tests the org.apache.commons.collections15.FactoryUtils class. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:39 $ * @since Commons Collections 3.0 */ public class TestFactoryUtils extends junit.framework.TestCase { /** * Construct */ public TestFactoryUtils(String name) { super(name); } /** * Main. * * @param args */ public static void main(String[] args) { TestRunner.run(suite()); } /** * Return class as a test suite. */ public static Test suite() { return new TestSuite(TestFactoryUtils.class); } /** * Set up instance variables required by this test case. */ public void setUp() { } /** * Tear down instance variables required by this test case. */ public void tearDown() { } // exceptionFactory //------------------------------------------------------------------ public void testExceptionFactory() { assertNotNull(FactoryUtils.exceptionFactory()); assertSame(FactoryUtils.exceptionFactory(), FactoryUtils.exceptionFactory()); try { FactoryUtils.exceptionFactory().create(); } catch (FunctorException ex) { try { FactoryUtils.exceptionFactory().create(); } catch (FunctorException ex2) { return; } } fail(); } // nullFactory //------------------------------------------------------------------ public void testNullFactory() { Factory factory = FactoryUtils.nullFactory(); assertNotNull(factory); Object created = factory.create(); assertNull(created); } // constantFactory //------------------------------------------------------------------ public void testConstantFactoryNull() { Factory factory = FactoryUtils.constantFactory(null); assertNotNull(factory); Object created = factory.create(); assertNull(created); } public void testConstantFactoryConstant() { Integer constant = new Integer(9); Factory factory = FactoryUtils.constantFactory(constant); assertNotNull(factory); Object created = factory.create(); assertSame(constant, created); } // prototypeFactory //------------------------------------------------------------------ public void testPrototypeFactoryNull() { assertSame(ConstantFactory.NULL_INSTANCE, FactoryUtils.prototypeFactory(null)); } public void testPrototypeFactoryPublicCloneMethod() throws Exception { Date proto = new Date(); Factory factory = FactoryUtils.prototypeFactory(proto); assertNotNull(factory); Object created = factory.create(); assertTrue(proto != created); assertEquals(proto, created); // check serialisation works ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(buffer); out.writeObject(factory); out.close(); ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(buffer.toByteArray())); Object dest = in.readObject(); in.close(); } public void testPrototypeFactoryPublicCopyConstructor() throws Exception { Mock1 proto = new Mock1(6); Factory factory = FactoryUtils.prototypeFactory(proto); assertNotNull(factory); Object created = factory.create(); assertTrue(proto != created); assertEquals(proto, created); // check serialisation works ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(buffer); try { out.writeObject(factory); } catch (NotSerializableException ex) { out.close(); } factory = FactoryUtils.prototypeFactory(new Mock2("S")); buffer = new ByteArrayOutputStream(); out = new ObjectOutputStream(buffer); out.writeObject(factory); out.close(); ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(buffer.toByteArray())); Object dest = in.readObject(); in.close(); } public void testPrototypeFactoryPublicSerialization() throws Exception { Integer proto = new Integer(9); Factory factory = FactoryUtils.prototypeFactory(proto); assertNotNull(factory); Object created = factory.create(); assertTrue(proto != created); assertEquals(proto, created); // check serialisation works ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(buffer); out.writeObject(factory); out.close(); ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(buffer.toByteArray())); Object dest = in.readObject(); in.close(); } public void testPrototypeFactoryPublicSerializationError() { Mock2 proto = new Mock2(new Object()); Factory factory = FactoryUtils.prototypeFactory(proto); assertNotNull(factory); try { Object created = factory.create(); } catch (FunctorException ex) { assertTrue(ex.getCause() instanceof IOException); return; } fail(); } public void testPrototypeFactoryPublicBad() { Object proto = new Object(); try { Factory factory = FactoryUtils.prototypeFactory(proto); } catch (IllegalArgumentException ex) { return; } fail(); } public static class Mock1 { private final int iVal; public Mock1(int val) { iVal = val; } public Mock1(Mock1 mock) { iVal = mock.iVal; } public boolean equals(Object obj) { if (obj instanceof Mock1) { if (iVal == ((Mock1) obj).iVal) { return true; } } return false; } } public static class Mock2 implements Serializable { private final Object iVal; public Mock2(Object val) { iVal = val; } public boolean equals(Object obj) { if (obj instanceof Mock2) { if (iVal == ((Mock2) obj).iVal) { return true; } } return false; } } public static class Mock3 { private static int cCounter = 0; private final int iVal; public Mock3() { iVal = cCounter++; } public int getValue() { return iVal; } } // instantiateFactory //------------------------------------------------------------------ public void testInstantiateFactoryNull() { try { Factory factory = FactoryUtils.instantiateFactory(null); } catch (IllegalArgumentException ex) { return; } fail(); } public void testInstantiateFactorySimple() { Factory factory = FactoryUtils.instantiateFactory(Mock3.class); assertNotNull(factory); Object created = factory.create(); assertEquals(0, ((Mock3) created).getValue()); created = factory.create(); assertEquals(1, ((Mock3) created).getValue()); } public void testInstantiateFactoryMismatch() { try { Factory factory = FactoryUtils.instantiateFactory(Date.class, null, new Object[]{null}); } catch (IllegalArgumentException ex) { return; } fail(); } public void testInstantiateFactoryNoConstructor() { try { Factory factory = FactoryUtils.instantiateFactory(Date.class, new Class[]{Long.class}, new Object[]{null}); } catch (IllegalArgumentException ex) { return; } fail(); } public void testInstantiateFactoryComplex() { TimeZone.setDefault(TimeZone.getTimeZone("GMT")); // 2nd Jan 1970 Factory factory = FactoryUtils.instantiateFactory(Date.class, new Class[]{Integer.TYPE, Integer.TYPE, Integer.TYPE}, new Object[]{new Integer(70), new Integer(0), new Integer(2)}); assertNotNull(factory); Object created = factory.create(); assertTrue(created instanceof Date); // long time of 1 day (== 2nd Jan 1970) assertEquals(new Date(1000 * 60 * 60 * 24), created); } } collections-generic-4.01/src/test/org/apache/commons/collections15/TestListUtils.java0000644000175000017500000000735610464140757031173 0ustar giovannigiovanni/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15; import junit.framework.Test; import org.apache.commons.collections15.list.PredicatedList; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; /** * Tests for ListUtils. * * @author Stephen Colebourne * @author Neil O'Toole * @author Matt Hall, John Watkinson, Matthew Hawthorne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:39 $ */ public class TestListUtils extends BulkTest { public TestListUtils(String name) { super(name); } public static Test suite() { return BulkTest.makeSuite(TestListUtils.class); } public void testNothing() { } public void testpredicatedList() { Predicate predicate = new Predicate() { public boolean evaluate(Object o) { return o instanceof String; } }; List list = ListUtils.predicatedList(new ArrayStack(), predicate); assertTrue("returned object should be a PredicatedList", list instanceof PredicatedList); try { list = ListUtils.predicatedList(new ArrayStack(), null); fail("Expecting IllegalArgumentException for null predicate."); } catch (IllegalArgumentException ex) { // expected } try { list = ListUtils.predicatedList(null, predicate); fail("Expecting IllegalArgumentException for null list."); } catch (IllegalArgumentException ex) { // expected } } public void testLazyList() { List list = ListUtils.lazyList(new ArrayList(), new Factory() { private int index; public Object create() { index++; return new Integer(index); } }); assertNotNull((Integer) list.get(5)); assertEquals(6, list.size()); assertNotNull((Integer) list.get(5)); assertEquals(6, list.size()); } public void testEquals() { Collection data = Arrays.asList(new String[]{"a", "b", "c"}); List a = new ArrayList(data); List b = new ArrayList(data); assertEquals(true, a.equals(b)); assertEquals(true, ListUtils.isEqualList(a, b)); a.clear(); assertEquals(false, ListUtils.isEqualList(a, b)); assertEquals(false, ListUtils.isEqualList(a, null)); assertEquals(false, ListUtils.isEqualList(null, b)); assertEquals(true, ListUtils.isEqualList(null, null)); } public void testHashCode() { Collection data = Arrays.asList(new String[]{"a", "b", "c"}); List a = new ArrayList(data); List b = new ArrayList(data); assertEquals(true, a.hashCode() == b.hashCode()); assertEquals(true, a.hashCode() == ListUtils.hashCodeForList(a)); assertEquals(true, b.hashCode() == ListUtils.hashCodeForList(b)); assertEquals(true, ListUtils.hashCodeForList(a) == ListUtils.hashCodeForList(b)); a.clear(); assertEquals(false, ListUtils.hashCodeForList(a) == ListUtils.hashCodeForList(b)); assertEquals(0, ListUtils.hashCodeForList(null)); } } collections-generic-4.01/src/test/org/apache/commons/collections15/TestFastTreeMap.java0000644000175000017500000000340110464140765031374 0ustar giovannigiovanni/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15; import junit.framework.Test; import java.util.Map; import java.util.TreeMap; import org.apache.commons.collections15.map.FastTreeMap; /** * Tests FastTreeMap. * * @author Matt Hall, John Watkinson, Jason van Zyl * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:39 $ */ public class TestFastTreeMap extends TestTreeMap { public TestFastTreeMap(String testName) { super(testName); } public static Test suite() { return BulkTest.makeSuite(TestFastTreeMap.class); } public static void main(String args[]) { String[] testCaseName = {TestFastTreeMap.class.getName()}; junit.textui.TestRunner.main(testCaseName); } public Map makeEmptyMap() { FastTreeMap ftm = new FastTreeMap(); ftm.setFast(false); return (ftm); } public Map makeConfirmedEmptyMap() { return new TreeMap(); } /** * The comparator for the fast tree map does not support null keys. */ public boolean isAllowNullKey() { return false; } public void setUp() { map = (TreeMap) makeEmptyMap(); } } collections-generic-4.01/src/test/org/apache/commons/collections15/TestMultiHashMap.java0000644000175000017500000003225610464140761031563 0ustar giovannigiovanni/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.collections15.map.AbstractTestMultiMap; import org.apache.commons.collections15.multimap.MultiHashMap; import java.util.*; /** * Unit Tests for MultiHashMap. * * @author Matt Hall, John Watkinson, Unknown * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:39 $ */ public class TestMultiHashMap extends AbstractTestMultiMap { public TestMultiHashMap(String testName) { super(testName); } public static Test suite() { return new TestSuite(TestMultiHashMap.class); } public static void main(String args[]) { String[] testCaseName = {TestMultiHashMap.class.getName()}; junit.textui.TestRunner.main(testCaseName); } // MutltiHashMap was introduced in Collections 2.x public String getCompatibilityVersion() { return "2"; } public MultiMap makeEmptyMap() { return new MultiHashMap(); } //---------------------------- // Tests //---------------------------- public void testPutNGet() { MultiHashMap map = new MultiHashMap(); loadMap(map); checkMap(map); assertTrue(map.get(new Integer(99)) == null); map.clear(); assertTrue(map.size() == 0); } public void testContainsValue() { MultiHashMap map = new MultiHashMap(); loadMap(map); assertTrue(map.containsValue("uno")); assertTrue(map.containsValue("quatro")); assertTrue(map.containsValue("two")); assertTrue(!map.containsValue("uggaBugga")); map.clear(); } public void testValues() { MultiHashMap map = new MultiHashMap(); loadMap(map); Collection vals = map.values(); assertTrue(vals.size() == getFullSize()); map.clear(); } static private class MapPair { MapPair(int key, String val) { mKey = new Integer(key); mValue = val; } Integer mKey = null; String mValue = null; } static private MapPair[][] sMapPairs = {{new MapPair(0, "zero")}, {new MapPair(1, "one"), new MapPair(1, "ONE"), new MapPair(1, "uno")}, {new MapPair(2, "two"), new MapPair(2, "two")}, {new MapPair(3, "three"), new MapPair(3, "THREE"), new MapPair(3, "tres")}, {new MapPair(4, "four"), new MapPair(4, "quatro")}}; private void loadMap(MultiHashMap map) { // Set up so that we load the keys "randomly" // (i.e. we don't want to load int row-order, so that all like keys // load together. We want to mix it up...) int numRows = sMapPairs.length; int maxCols = 0; for (int ii = 0; ii < sMapPairs.length; ii++) { if (sMapPairs[ii].length > maxCols) { maxCols = sMapPairs[ii].length; } } for (int ii = 0; ii < maxCols; ii++) { for (int jj = 0; jj < numRows; jj++) { if (ii < sMapPairs[jj].length) { map.put(sMapPairs[jj][ii].mKey, sMapPairs[jj][ii].mValue); //--------------------------------------------------------- } } } assertTrue(map.size() == sMapPairs.length); } private void checkMap(MultiHashMap map) { for (int ii = 0; ii < sMapPairs.length; ii++) { checkKeyList(map, ii); } } private void checkKeyList(MultiHashMap map, int index) { assertTrue(index < sMapPairs.length); Integer key = sMapPairs[index][0].mKey; Object obj = map.get(key); //-------------------------- assertTrue(obj != null); assertTrue(obj instanceof Collection); Collection keyList = (Collection) obj; assertTrue(keyList.size() == sMapPairs[index].length); Iterator iter = keyList.iterator(); while (iter.hasNext()) { Object oval = iter.next(); assertTrue(oval != null); assertTrue(oval instanceof String); String val = (String) oval; boolean foundIt = false; for (int ii = 0; ii < sMapPairs[index].length; ii++) { if (val.equals(sMapPairs[index][ii].mValue)) { foundIt = true; } } assertTrue(foundIt); } } public int getFullSize() { int len = 0; for (int ii = 0; ii < sMapPairs.length; ii++) { len += sMapPairs[ii].length; } return len; } public void testEntrySetIterator() { } public void testEntrySetContainsProperMappings() { } public void testEntrySetIteratorHasProperMappings() { // override and ignore test -- it will fail when verifying the iterator for // the set contains the right value -- we're not returning the value, we're // returning a collection. // TODO: re-implement this test to ensure the values of the iterator match // the proper collection rather than the value the superclass is checking // for. return; } // Next methods are overriden because MultiHashMap values are always a // collection, and deviate from the Map contract because of this. // TODO: implement the tests to ensure that Map.get(Object) returns the // appropriate collection of values public void testMapGet() { } public void testMapPut() { } public void testMapPutAll() { } public void testMapRemove() { } public void testMapEquals() { MultiHashMap one = new MultiHashMap(); Integer value = new Integer(1); one.put("One", value); one.remove("One", value); MultiHashMap two = new MultiHashMap(); assertEquals(two, one); } public void testMapHashCode() { } // The verification for the map and its entry set must also be overridden // because the values are not going to be the same as the values in the // confirmed map (they're going to be collections15 of values instead). public void verifyMap() { // TODO: implement test to ensure that map is the same as confirmed if // its values were converted into collections15. } public void verifyEntrySet() { // TODO: implement test to ensure that each entry is the same as one in // the confirmed map, but with the value wrapped in a collection. } // The verification method must be overridden because MultiHashMap's // values() is not properly backed by the map (Bug 9573). public void verifyValues() { // update the values view to the latest version, then proceed to verify // as usual. values = map.values(); super.verifyValues(); } //----------------------------------------------------------------------- public void testGetCollection() { MultiHashMap map = new MultiHashMap(); map.put("A", "AA"); assertSame(map.get("A"), map.getCollection("A")); } public void testTotalSize() { MultiHashMap map = new MultiHashMap(); assertEquals(0, map.totalSize()); map.put("A", "AA"); assertEquals(1, map.totalSize()); map.put("B", "BA"); assertEquals(2, map.totalSize()); map.put("B", "BB"); assertEquals(3, map.totalSize()); map.put("B", "BC"); assertEquals(4, map.totalSize()); map.remove("A"); assertEquals(3, map.totalSize()); map.remove("B", "BC"); assertEquals(2, map.totalSize()); } public void testSize_Key() { MultiHashMap map = new MultiHashMap(); assertEquals(0, map.size("A")); assertEquals(0, map.size("B")); map.put("A", "AA"); assertEquals(1, map.size("A")); assertEquals(0, map.size("B")); map.put("B", "BA"); assertEquals(1, map.size("A")); assertEquals(1, map.size("B")); map.put("B", "BB"); assertEquals(1, map.size("A")); assertEquals(2, map.size("B")); map.put("B", "BC"); assertEquals(1, map.size("A")); assertEquals(3, map.size("B")); map.remove("A"); assertEquals(0, map.size("A")); assertEquals(3, map.size("B")); map.remove("B", "BC"); assertEquals(0, map.size("A")); assertEquals(2, map.size("B")); } public void testIterator_Key() { MultiHashMap map = new MultiHashMap(); assertEquals(false, map.iterator("A").hasNext()); map.put("A", "AA"); Iterator it = map.iterator("A"); assertEquals(true, it.hasNext()); it.next(); assertEquals(false, it.hasNext()); } public void testContainsValue_Key() { MultiHashMap map = new MultiHashMap(); assertEquals(false, map.containsValue("A", "AA")); assertEquals(false, map.containsValue("B", "BB")); map.put("A", "AA"); assertEquals(true, map.containsValue("A", "AA")); assertEquals(false, map.containsValue("A", "AB")); } public void testPutAll_KeyCollection() { MultiHashMap map = new MultiHashMap(); Collection coll = Arrays.asList(new Object[]{"X", "Y", "Z"}); assertEquals(true, map.putAll("A", coll)); assertEquals(3, map.size("A")); assertEquals(true, map.containsValue("A", "X")); assertEquals(true, map.containsValue("A", "Y")); assertEquals(true, map.containsValue("A", "Z")); assertEquals(false, map.putAll("A", null)); assertEquals(3, map.size("A")); assertEquals(true, map.containsValue("A", "X")); assertEquals(true, map.containsValue("A", "Y")); assertEquals(true, map.containsValue("A", "Z")); assertEquals(false, map.putAll("A", new ArrayList())); assertEquals(3, map.size("A")); assertEquals(true, map.containsValue("A", "X")); assertEquals(true, map.containsValue("A", "Y")); assertEquals(true, map.containsValue("A", "Z")); coll = Arrays.asList(new Object[]{"M"}); assertEquals(true, map.putAll("A", coll)); assertEquals(4, map.size("A")); assertEquals(true, map.containsValue("A", "X")); assertEquals(true, map.containsValue("A", "Y")); assertEquals(true, map.containsValue("A", "Z")); assertEquals(true, map.containsValue("A", "M")); } public void testClone() { MultiHashMap map = new MultiHashMap(); map.put("A", "1"); map.put("A", "2"); Collection coll = (Collection) map.get("A"); assertEquals(1, map.size()); assertEquals(2, coll.size()); MultiHashMap cloned = (MultiHashMap) map.clone(); Collection clonedColl = (Collection) cloned.get("A"); assertNotSame(map, cloned); assertNotSame(coll, clonedColl); assertEquals(1, map.size()); assertEquals(2, coll.size()); assertEquals(1, cloned.size()); assertEquals(2, clonedColl.size()); map.put("A", "3"); assertEquals(1, map.size()); assertEquals(3, coll.size()); assertEquals(1, cloned.size()); assertEquals(2, clonedColl.size()); } public void testConstructorCopy1() { MultiHashMap map = new MultiHashMap(); map.put("A", "1"); map.put("A", "2"); Collection coll = (Collection) map.get("A"); assertEquals(1, map.size()); assertEquals(2, coll.size()); MultiHashMap newMap = new MultiHashMap(map); Collection newColl = (Collection) newMap.get("A"); assertNotSame(map, newMap); assertNotSame(coll, newColl); assertEquals(1, map.size()); assertEquals(2, coll.size()); assertEquals(1, newMap.size()); assertEquals(2, newColl.size()); map.put("A", "3"); assertEquals(1, map.size()); assertEquals(3, coll.size()); assertEquals(1, newMap.size()); assertEquals(2, newColl.size()); } public void testConstructorCopy2() { Map map = new HashMap(); map.put("A", "1"); map.put("B", "2"); assertEquals(2, map.size()); MultiHashMap newMap = new MultiHashMap(map); Collection newColl = (Collection) newMap.get("A"); assertNotSame(map, newMap); assertEquals(2, map.size()); assertEquals(2, newMap.size()); assertEquals(1, newColl.size()); map.put("A", "3"); assertEquals(2, map.size()); assertEquals(2, newMap.size()); assertEquals(1, newColl.size()); map.put("C", "4"); assertEquals(3, map.size()); assertEquals(2, newMap.size()); assertEquals(1, newColl.size()); } } collections-generic-4.01/src/test/org/apache/commons/collections15/TestBeanMap.java0000644000175000017500000002451210464140760030525 0ustar giovannigiovanni/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15; import junit.framework.Test; import junit.textui.TestRunner; import org.apache.commons.collections15.map.AbstractTestMap; import java.io.Serializable; import java.lang.reflect.Method; import java.util.Map; /** * Test cases for BeanMap * * @author Morgan Delagrange * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:39 $ */ public class TestBeanMap extends AbstractTestMap { public TestBeanMap(String testName) { super(testName); } public static void main(String[] args) { TestRunner.run(suite()); } public static Test suite() { return BulkTest.makeSuite(TestBeanMap.class); } /* note to self. The getter and setter methods were generated by copying the field declarations and using the following regular expression search and replace: From: private \(.*\) some\(.*\); To: public \1 getSome\2Value() { return some\2; } public void setSome\2Value(\1 value) { some\2 = value; } Also note: The sample keys and mappings were generated manually. */ public static class BeanWithProperties implements Serializable { private int someInt; private long someLong; private double someDouble; private float someFloat; private short someShort; private byte someByte; private char someChar; private Integer someInteger; private String someString; private Object someObject; public int getSomeIntValue() { return someInt; } public void setSomeIntValue(int value) { someInt = value; } public long getSomeLongValue() { return someLong; } public void setSomeLongValue(long value) { someLong = value; } public double getSomeDoubleValue() { return someDouble; } public void setSomeDoubleValue(double value) { someDouble = value; } public float getSomeFloatValue() { return someFloat; } public void setSomeFloatValue(float value) { someFloat = value; } public short getSomeShortValue() { return someShort; } public void setSomeShortValue(short value) { someShort = value; } public byte getSomeByteValue() { return someByte; } public void setSomeByteValue(byte value) { someByte = value; } public char getSomeCharValue() { return someChar; } public void setSomeCharValue(char value) { someChar = value; } public String getSomeStringValue() { return someString; } public void setSomeStringValue(String value) { someString = value; } public Integer getSomeIntegerValue() { return someInteger; } public void setSomeIntegerValue(Integer value) { someInteger = value; } public Object getSomeObjectValue() { return someObject; } public void setSomeObjectValue(Object value) { someObject = value; } } // note to self. The Sample keys were generated by copying the field // declarations and using the following regular expression search and replace: // // From: // private \(.*\) some\(.*\); // To: // "some\2Value", // // Then, I manually added the "class" key, which is a property that exists for // all beans (and all objects for that matter. public Object[] getSampleKeys() { Object[] keys = new Object[]{"someIntValue", "someLongValue", "someDoubleValue", "someFloatValue", "someShortValue", "someByteValue", "someCharValue", "someIntegerValue", "someStringValue", "someObjectValue", "class", }; return keys; } /** * An object value that will be stored in the bean map as a value. Need * to save this externally so that we can make sure the object instances * are equivalent since getSampleValues() would otherwise construct a new * and different Object each time. */ private Object objectInFullMap = new Object(); // note to self: the sample values were created manually public Object[] getSampleValues() { Object[] values = new Object[]{new Integer(1234), new Long(1298341928234L), new Double(123423.34), new Float(1213332.12f), new Short((short) 134), new Byte((byte) 10), new Character('a'), new Integer(1432), "SomeStringValue", objectInFullMap, BeanWithProperties.class, }; return values; } public Object[] getNewSampleValues() { Object[] values = new Object[]{new Integer(223), new Long(23341928234L), new Double(23423.34), new Float(213332.12f), new Short((short) 234), new Byte((byte) 20), new Character('b'), new Integer(232), "SomeNewStringValue", new Object(), null, }; return values; } /** * Values is a dead copy in BeanMap, so refresh each time. */ public void verifyValues() { values = map.values(); super.verifyValues(); } /** * The mappings in a BeanMap are fixed on the properties the underlying * bean has. Adding and removing mappings is not possible, thus this * method is overridden to return false. */ public boolean isPutAddSupported() { return false; } /** * The mappings in a BeanMap are fixed on the properties the underlying * bean has. Adding and removing mappings is not possible, thus this * method is overridden to return false. */ public boolean isRemoveSupported() { return false; } public Map makeFullMap() { // note: These values must match (i.e. .equals() must return true) // those returned from getSampleValues(). BeanWithProperties bean = new BeanWithProperties(); bean.setSomeIntValue(1234); bean.setSomeLongValue(1298341928234L); bean.setSomeDoubleValue(123423.34); bean.setSomeFloatValue(1213332.12f); bean.setSomeShortValue((short) 134); bean.setSomeByteValue((byte) 10); bean.setSomeCharValue('a'); bean.setSomeIntegerValue(new Integer(1432)); bean.setSomeStringValue("SomeStringValue"); bean.setSomeObjectValue(objectInFullMap); return new BeanMap(bean); } public Map makeEmptyMap() { return new BeanMap(); } public String[] ignoredTests() { // Ignore the serialization tests on collection views. return new String[]{"TestBeanMap.bulkTestMapEntrySet.testCanonicalEmptyCollectionExists", "TestBeanMap.bulkTestMapEntrySet.testCanonicalFullCollectionExists", "TestBeanMap.bulkTestMapKeySet.testCanonicalEmptyCollectionExists", "TestBeanMap.bulkTestMapKeySet.testCanonicalFullCollectionExists", "TestBeanMap.bulkTestMapValues.testCanonicalEmptyCollectionExists", "TestBeanMap.bulkTestMapValues.testCanonicalFullCollectionExists", "TestBeanMap.bulkTestMapEntrySet.testSimpleSerialization", "TestBeanMap.bulkTestMapKeySet.testSimpleSerialization", "TestBeanMap.bulkTestMapEntrySet.testSerializeDeserializeThenCompare", "TestBeanMap.bulkTestMapKeySet.testSerializeDeserializeThenCompare"}; } /** * Need to override this method because the "clear()" method on the bean * map just returns the bean properties to their default states. It does * not actually remove the mappings as per the map contract. The default * testClear() methods checks that the clear method throws an * UnsupportedOperationException since this class is not add/remove * modifiable. In our case though, we do not always throw that exception. */ public void testMapClear() { //TODO: make sure a call to BeanMap.clear returns the bean to its //default initialization values. } /** * Need to override this method because the "put()" method on the bean * doesn't work for this type of Map. */ public void testMapPut() { // see testBeanMapPutAllWriteable } public void testBeanMapClone() { BeanMap map = (BeanMap) makeFullMap(); try { BeanMap map2 = (BeanMap) ((BeanMap) map).clone(); // make sure containsKey is working to verify the bean was cloned // ok, and the read methods were properly initialized Object[] keys = getSampleKeys(); for (int i = 0; i < keys.length; i++) { assertTrue("Cloned BeanMap should contain the same keys", map2.containsKey(keys[i])); } } catch (CloneNotSupportedException exception) { fail("BeanMap.clone() should not throw a " + "CloneNotSupportedException when clone should succeed."); } } public void testBeanMapPutAllWriteable() { BeanMap map1 = (BeanMap) makeFullMap(); BeanMap map2 = (BeanMap) makeFullMap(); map2.put("someIntValue", new Integer(0)); map1.putAllWriteable(map2); assertEquals(map1.get("someIntValue"), new Integer(0)); } public void testMethodAccessor() throws Exception { BeanMap map = (BeanMap) makeFullMap(); Method method = BeanWithProperties.class.getDeclaredMethod("getSomeIntegerValue", null); assertEquals(method, map.getReadMethod("someIntegerValue")); } public void testMethodMutator() throws Exception { BeanMap map = (BeanMap) makeFullMap(); Method method = BeanWithProperties.class.getDeclaredMethod("setSomeIntegerValue", new Class[]{Integer.class}); assertEquals(method, map.getWriteMethod("someIntegerValue")); } } collections-generic-4.01/src/test/org/apache/commons/collections15/TestPredicateUtils.java0000644000175000017500000007640210464140757032156 0ustar giovannigiovanni/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15; import junit.framework.Test; import junit.framework.TestSuite; import junit.textui.TestRunner; import java.util.*; /** * Tests the org.apache.commons.collections15.PredicateUtils class. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:39 $ * @since Commons Collections 3.0 */ public class TestPredicateUtils extends junit.framework.TestCase { private static final Object cObject = new Object(); private static final String cString = "Hello"; private static final Integer cInteger = new Integer(6); /** * Construct */ public TestPredicateUtils(String name) { super(name); } /** * Main. * * @param args */ public static void main(String[] args) { TestRunner.run(suite()); } /** * Return class as a test suite. */ public static Test suite() { return new TestSuite(TestPredicateUtils.class); } /** * Set up instance variables required by this test case. */ public void setUp() { } /** * Tear down instance variables required by this test case. */ public void tearDown() { } // exceptionPredicate //------------------------------------------------------------------ public void testExceptionPredicate() { assertNotNull(PredicateUtils.exceptionPredicate()); assertSame(PredicateUtils.exceptionPredicate(), PredicateUtils.exceptionPredicate()); try { PredicateUtils.exceptionPredicate().evaluate(null); } catch (FunctorException ex) { try { PredicateUtils.exceptionPredicate().evaluate(cString); } catch (FunctorException ex2) { return; } } fail(); } // nullPredicate //------------------------------------------------------------------ public void testNullPredicate() { assertNotNull(PredicateUtils.nullPredicate()); assertSame(PredicateUtils.nullPredicate(), PredicateUtils.nullPredicate()); assertEquals(true, PredicateUtils.nullPredicate().evaluate(null)); assertEquals(false, PredicateUtils.nullPredicate().evaluate(cObject)); assertEquals(false, PredicateUtils.nullPredicate().evaluate(cString)); assertEquals(false, PredicateUtils.nullPredicate().evaluate(cInteger)); } // notNullPredicate //------------------------------------------------------------------ public void testIsNotNullPredicate() { assertNotNull(PredicateUtils.notNullPredicate()); assertSame(PredicateUtils.notNullPredicate(), PredicateUtils.notNullPredicate()); assertEquals(false, PredicateUtils.notNullPredicate().evaluate(null)); assertEquals(true, PredicateUtils.notNullPredicate().evaluate(cObject)); assertEquals(true, PredicateUtils.notNullPredicate().evaluate(cString)); assertEquals(true, PredicateUtils.notNullPredicate().evaluate(cInteger)); } // equalPredicate //------------------------------------------------------------------ public void testEqualPredicate() { assertSame(PredicateUtils.nullPredicate(), PredicateUtils.equalPredicate(null)); assertNotNull(PredicateUtils.equalPredicate(new Integer(6))); assertEquals(false, PredicateUtils.equalPredicate(new Integer(6)).evaluate(null)); // GenericsNote: Test no longer applicable. //assertEquals(false, PredicateUtils.equalPredicate(new Integer(6)).evaluate(cObject)); //assertEquals(false, PredicateUtils.equalPredicate(new Integer(6)).evaluate(cString)); assertEquals(true, PredicateUtils.equalPredicate(new Integer(6)).evaluate(cInteger)); } // identityPredicate //------------------------------------------------------------------ public void testIdentityPredicate() { assertSame(PredicateUtils.nullPredicate(), PredicateUtils.identityPredicate(null)); assertNotNull(PredicateUtils.identityPredicate(new Integer(6))); assertEquals(false, PredicateUtils.identityPredicate(new Integer(6)).evaluate(null)); // GenericsNote: Test no longer applicable. //assertEquals(false, PredicateUtils.identityPredicate(new Integer(6)).evaluate(cObject)); //assertEquals(false, PredicateUtils.identityPredicate(new Integer(6)).evaluate(cString)); assertEquals(false, PredicateUtils.identityPredicate(new Integer(6)).evaluate(cInteger)); assertEquals(true, PredicateUtils.identityPredicate(cInteger).evaluate(cInteger)); } // truePredicate //------------------------------------------------------------------ public void testTruePredicate() { assertNotNull(PredicateUtils.truePredicate()); assertSame(PredicateUtils.truePredicate(), PredicateUtils.truePredicate()); assertEquals(true, PredicateUtils.truePredicate().evaluate(null)); assertEquals(true, PredicateUtils.truePredicate().evaluate(cObject)); assertEquals(true, PredicateUtils.truePredicate().evaluate(cString)); assertEquals(true, PredicateUtils.truePredicate().evaluate(cInteger)); } // falsePredicate //------------------------------------------------------------------ public void testFalsePredicate() { assertNotNull(PredicateUtils.falsePredicate()); assertSame(PredicateUtils.falsePredicate(), PredicateUtils.falsePredicate()); assertEquals(false, PredicateUtils.falsePredicate().evaluate(null)); assertEquals(false, PredicateUtils.falsePredicate().evaluate(cObject)); assertEquals(false, PredicateUtils.falsePredicate().evaluate(cString)); assertEquals(false, PredicateUtils.falsePredicate().evaluate(cInteger)); } // notPredicate //------------------------------------------------------------------ public void testNotPredicate() { assertNotNull(PredicateUtils.notPredicate(PredicateUtils.truePredicate())); assertEquals(false, PredicateUtils.notPredicate(PredicateUtils.truePredicate()).evaluate(null)); assertEquals(false, PredicateUtils.notPredicate(PredicateUtils.truePredicate()).evaluate(cObject)); assertEquals(false, PredicateUtils.notPredicate(PredicateUtils.truePredicate()).evaluate(cString)); assertEquals(false, PredicateUtils.notPredicate(PredicateUtils.truePredicate()).evaluate(cInteger)); } public void testNotPredicateEx() { try { PredicateUtils.notPredicate(null); } catch (IllegalArgumentException ex) { return; } fail(); } // andPredicate //------------------------------------------------------------------ public void testAndPredicate() { assertEquals(true, PredicateUtils.andPredicate(PredicateUtils.truePredicate(), PredicateUtils.truePredicate()).evaluate(null)); assertEquals(false, PredicateUtils.andPredicate(PredicateUtils.truePredicate(), PredicateUtils.falsePredicate()).evaluate(null)); assertEquals(false, PredicateUtils.andPredicate(PredicateUtils.falsePredicate(), PredicateUtils.truePredicate()).evaluate(null)); assertEquals(false, PredicateUtils.andPredicate(PredicateUtils.falsePredicate(), PredicateUtils.falsePredicate()).evaluate(null)); } public void testAndPredicateEx() { try { PredicateUtils.andPredicate(null, null); } catch (IllegalArgumentException ex) { return; } fail(); } // allPredicate //------------------------------------------------------------------ public void testAllPredicate() { assertEquals(true, PredicateUtils.allPredicate(new Predicate[]{PredicateUtils.truePredicate(), PredicateUtils.truePredicate(), PredicateUtils.truePredicate()}).evaluate(null)); assertEquals(false, PredicateUtils.allPredicate(new Predicate[]{PredicateUtils.truePredicate(), PredicateUtils.falsePredicate(), PredicateUtils.truePredicate()}).evaluate(null)); assertEquals(false, PredicateUtils.allPredicate(new Predicate[]{PredicateUtils.falsePredicate(), PredicateUtils.falsePredicate(), PredicateUtils.truePredicate()}).evaluate(null)); assertEquals(false, PredicateUtils.allPredicate(new Predicate[]{PredicateUtils.falsePredicate(), PredicateUtils.falsePredicate(), PredicateUtils.falsePredicate()}).evaluate(null)); Collection coll = new ArrayList(); coll.add(PredicateUtils.truePredicate()); coll.add(PredicateUtils.truePredicate()); coll.add(PredicateUtils.truePredicate()); assertEquals(true, PredicateUtils.allPredicate(coll).evaluate(null)); coll.clear(); coll.add(PredicateUtils.truePredicate()); coll.add(PredicateUtils.falsePredicate()); coll.add(PredicateUtils.truePredicate()); assertEquals(false, PredicateUtils.allPredicate(coll).evaluate(null)); coll.clear(); coll.add(PredicateUtils.falsePredicate()); coll.add(PredicateUtils.falsePredicate()); coll.add(PredicateUtils.truePredicate()); assertEquals(false, PredicateUtils.allPredicate(coll).evaluate(null)); coll.clear(); coll.add(PredicateUtils.falsePredicate()); coll.add(PredicateUtils.falsePredicate()); coll.add(PredicateUtils.falsePredicate()); assertEquals(false, PredicateUtils.allPredicate(coll).evaluate(null)); } public void testAllPredicateEx1() { try { PredicateUtils.allPredicate((Predicate[]) null); } catch (IllegalArgumentException ex) { return; } fail(); } public void testAllPredicateEx2() { try { PredicateUtils.allPredicate(new Predicate[]{null}); } catch (IllegalArgumentException ex) { return; } fail(); } public void testAllPredicateEx3() { try { PredicateUtils.allPredicate(new Predicate[]{null, null}); } catch (IllegalArgumentException ex) { return; } fail(); } public void testAllPredicateEx4() { try { PredicateUtils.allPredicate((Collection) null); } catch (IllegalArgumentException ex) { return; } fail(); } public void testAllPredicateEx5() { try { PredicateUtils.allPredicate(Collections.EMPTY_LIST); } catch (IllegalArgumentException ex) { return; } fail(); } public void testAllPredicateEx6() { try { Collection coll = new ArrayList(); coll.add(null); coll.add(null); PredicateUtils.allPredicate(coll); } catch (IllegalArgumentException ex) { return; } fail(); } // orPredicate //------------------------------------------------------------------ public void testOrPredicate() { assertEquals(true, PredicateUtils.orPredicate(PredicateUtils.truePredicate(), PredicateUtils.truePredicate()).evaluate(null)); assertEquals(true, PredicateUtils.orPredicate(PredicateUtils.truePredicate(), PredicateUtils.falsePredicate()).evaluate(null)); assertEquals(true, PredicateUtils.orPredicate(PredicateUtils.falsePredicate(), PredicateUtils.truePredicate()).evaluate(null)); assertEquals(false, PredicateUtils.orPredicate(PredicateUtils.falsePredicate(), PredicateUtils.falsePredicate()).evaluate(null)); } public void testOrPredicateEx() { try { PredicateUtils.orPredicate(null, null); } catch (IllegalArgumentException ex) { return; } fail(); } // anyPredicate //------------------------------------------------------------------ public void testAnyPredicate() { assertEquals(true, PredicateUtils.anyPredicate(new Predicate[]{PredicateUtils.truePredicate(), PredicateUtils.truePredicate(), PredicateUtils.truePredicate()}).evaluate(null)); assertEquals(true, PredicateUtils.anyPredicate(new Predicate[]{PredicateUtils.truePredicate(), PredicateUtils.falsePredicate(), PredicateUtils.truePredicate()}).evaluate(null)); assertEquals(true, PredicateUtils.anyPredicate(new Predicate[]{PredicateUtils.falsePredicate(), PredicateUtils.falsePredicate(), PredicateUtils.truePredicate()}).evaluate(null)); assertEquals(false, PredicateUtils.anyPredicate(new Predicate[]{PredicateUtils.falsePredicate(), PredicateUtils.falsePredicate(), PredicateUtils.falsePredicate()}).evaluate(null)); Collection coll = new ArrayList(); coll.add(PredicateUtils.truePredicate()); coll.add(PredicateUtils.truePredicate()); coll.add(PredicateUtils.truePredicate()); assertEquals(true, PredicateUtils.anyPredicate(coll).evaluate(null)); coll.clear(); coll.add(PredicateUtils.truePredicate()); coll.add(PredicateUtils.falsePredicate()); coll.add(PredicateUtils.truePredicate()); assertEquals(true, PredicateUtils.anyPredicate(coll).evaluate(null)); coll.clear(); coll.add(PredicateUtils.falsePredicate()); coll.add(PredicateUtils.falsePredicate()); coll.add(PredicateUtils.truePredicate()); assertEquals(true, PredicateUtils.anyPredicate(coll).evaluate(null)); coll.clear(); coll.add(PredicateUtils.falsePredicate()); coll.add(PredicateUtils.falsePredicate()); coll.add(PredicateUtils.falsePredicate()); assertEquals(false, PredicateUtils.anyPredicate(coll).evaluate(null)); } public void testAnyPredicateEx1() { try { PredicateUtils.anyPredicate((Predicate[]) null); } catch (IllegalArgumentException ex) { return; } fail(); } public void testAnyPredicateEx2() { try { PredicateUtils.anyPredicate(new Predicate[]{null}); } catch (IllegalArgumentException ex) { return; } fail(); } public void testAnyPredicateEx3() { try { PredicateUtils.anyPredicate(new Predicate[]{null, null}); } catch (IllegalArgumentException ex) { return; } fail(); } public void testAnyPredicateEx4() { try { PredicateUtils.anyPredicate((Collection) null); } catch (IllegalArgumentException ex) { return; } fail(); } public void testAnyPredicateEx5() { try { PredicateUtils.anyPredicate(Collections.EMPTY_LIST); } catch (IllegalArgumentException ex) { return; } fail(); } public void testAnyPredicateEx6() { try { Collection coll = new ArrayList(); coll.add(null); coll.add(null); PredicateUtils.anyPredicate(coll); } catch (IllegalArgumentException ex) { return; } fail(); } // eitherPredicate //------------------------------------------------------------------ public void testEitherPredicate() { assertEquals(false, PredicateUtils.eitherPredicate(PredicateUtils.truePredicate(), PredicateUtils.truePredicate()).evaluate(null)); assertEquals(true, PredicateUtils.eitherPredicate(PredicateUtils.truePredicate(), PredicateUtils.falsePredicate()).evaluate(null)); assertEquals(true, PredicateUtils.eitherPredicate(PredicateUtils.falsePredicate(), PredicateUtils.truePredicate()).evaluate(null)); assertEquals(false, PredicateUtils.eitherPredicate(PredicateUtils.falsePredicate(), PredicateUtils.falsePredicate()).evaluate(null)); } public void testEitherPredicateEx() { try { PredicateUtils.eitherPredicate(null, null); } catch (IllegalArgumentException ex) { return; } fail(); } // onePredicate //------------------------------------------------------------------ public void testOnePredicate() { assertEquals(false, PredicateUtils.onePredicate(new Predicate[]{PredicateUtils.truePredicate(), PredicateUtils.truePredicate(), PredicateUtils.truePredicate()}).evaluate(null)); assertEquals(false, PredicateUtils.onePredicate(new Predicate[]{PredicateUtils.truePredicate(), PredicateUtils.falsePredicate(), PredicateUtils.truePredicate()}).evaluate(null)); assertEquals(true, PredicateUtils.onePredicate(new Predicate[]{PredicateUtils.truePredicate(), PredicateUtils.falsePredicate(), PredicateUtils.falsePredicate()}).evaluate(null)); assertEquals(true, PredicateUtils.onePredicate(new Predicate[]{PredicateUtils.falsePredicate(), PredicateUtils.truePredicate(), PredicateUtils.falsePredicate()}).evaluate(null)); assertEquals(true, PredicateUtils.onePredicate(new Predicate[]{PredicateUtils.falsePredicate(), PredicateUtils.falsePredicate(), PredicateUtils.truePredicate()}).evaluate(null)); assertEquals(false, PredicateUtils.onePredicate(new Predicate[]{PredicateUtils.falsePredicate(), PredicateUtils.falsePredicate(), PredicateUtils.falsePredicate()}).evaluate(null)); Collection coll = new ArrayList(); coll.add(PredicateUtils.truePredicate()); coll.add(PredicateUtils.truePredicate()); coll.add(PredicateUtils.truePredicate()); assertEquals(false, PredicateUtils.onePredicate(coll).evaluate(null)); coll.clear(); coll.add(PredicateUtils.truePredicate()); coll.add(PredicateUtils.falsePredicate()); coll.add(PredicateUtils.truePredicate()); assertEquals(false, PredicateUtils.onePredicate(coll).evaluate(null)); coll.clear(); coll.add(PredicateUtils.falsePredicate()); coll.add(PredicateUtils.falsePredicate()); coll.add(PredicateUtils.truePredicate()); assertEquals(true, PredicateUtils.onePredicate(coll).evaluate(null)); coll.clear(); coll.add(PredicateUtils.falsePredicate()); coll.add(PredicateUtils.falsePredicate()); coll.add(PredicateUtils.falsePredicate()); assertEquals(false, PredicateUtils.onePredicate(coll).evaluate(null)); } public void testOnePredicateEx1() { try { PredicateUtils.onePredicate((Predicate[]) null); } catch (IllegalArgumentException ex) { return; } fail(); } public void testOnePredicateEx2() { try { PredicateUtils.onePredicate(new Predicate[]{null}); } catch (IllegalArgumentException ex) { return; } fail(); } public void testOnePredicateEx3() { try { PredicateUtils.onePredicate(new Predicate[]{null, null}); } catch (IllegalArgumentException ex) { return; } fail(); } public void testOnePredicateEx4() { try { PredicateUtils.onePredicate((Collection) null); } catch (IllegalArgumentException ex) { return; } fail(); } public void testOnePredicateEx5() { try { PredicateUtils.onePredicate(Collections.EMPTY_LIST); } catch (IllegalArgumentException ex) { return; } fail(); } public void testOnePredicateEx6() { try { Collection coll = new ArrayList(); coll.add(null); coll.add(null); PredicateUtils.onePredicate(coll); } catch (IllegalArgumentException ex) { return; } fail(); } // neitherPredicate //------------------------------------------------------------------ public void testNeitherPredicate() { assertEquals(false, PredicateUtils.neitherPredicate(PredicateUtils.truePredicate(), PredicateUtils.truePredicate()).evaluate(null)); assertEquals(false, PredicateUtils.neitherPredicate(PredicateUtils.truePredicate(), PredicateUtils.falsePredicate()).evaluate(null)); assertEquals(false, PredicateUtils.neitherPredicate(PredicateUtils.falsePredicate(), PredicateUtils.truePredicate()).evaluate(null)); assertEquals(true, PredicateUtils.neitherPredicate(PredicateUtils.falsePredicate(), PredicateUtils.falsePredicate()).evaluate(null)); } public void testNeitherPredicateEx() { try { PredicateUtils.neitherPredicate(null, null); } catch (IllegalArgumentException ex) { return; } fail(); } // nonePredicate //------------------------------------------------------------------ public void testNonePredicate() { assertEquals(false, PredicateUtils.nonePredicate(new Predicate[]{PredicateUtils.truePredicate(), PredicateUtils.truePredicate(), PredicateUtils.truePredicate()}).evaluate(null)); assertEquals(false, PredicateUtils.nonePredicate(new Predicate[]{PredicateUtils.truePredicate(), PredicateUtils.falsePredicate(), PredicateUtils.truePredicate()}).evaluate(null)); assertEquals(false, PredicateUtils.nonePredicate(new Predicate[]{PredicateUtils.falsePredicate(), PredicateUtils.falsePredicate(), PredicateUtils.truePredicate()}).evaluate(null)); assertEquals(true, PredicateUtils.nonePredicate(new Predicate[]{PredicateUtils.falsePredicate(), PredicateUtils.falsePredicate(), PredicateUtils.falsePredicate()}).evaluate(null)); Collection coll = new ArrayList(); coll.add(PredicateUtils.truePredicate()); coll.add(PredicateUtils.truePredicate()); coll.add(PredicateUtils.truePredicate()); assertEquals(false, PredicateUtils.nonePredicate(coll).evaluate(null)); coll.clear(); coll.add(PredicateUtils.truePredicate()); coll.add(PredicateUtils.falsePredicate()); coll.add(PredicateUtils.truePredicate()); assertEquals(false, PredicateUtils.nonePredicate(coll).evaluate(null)); coll.clear(); coll.add(PredicateUtils.falsePredicate()); coll.add(PredicateUtils.falsePredicate()); coll.add(PredicateUtils.truePredicate()); assertEquals(false, PredicateUtils.nonePredicate(coll).evaluate(null)); coll.clear(); coll.add(PredicateUtils.falsePredicate()); coll.add(PredicateUtils.falsePredicate()); coll.add(PredicateUtils.falsePredicate()); assertEquals(true, PredicateUtils.nonePredicate(coll).evaluate(null)); } public void testNonePredicateEx1() { try { PredicateUtils.nonePredicate((Predicate[]) null); } catch (IllegalArgumentException ex) { return; } fail(); } public void testNonePredicateEx2() { try { PredicateUtils.nonePredicate(new Predicate[]{null}); } catch (IllegalArgumentException ex) { return; } fail(); } public void testNonePredicateEx3() { try { PredicateUtils.nonePredicate(new Predicate[]{null, null}); } catch (IllegalArgumentException ex) { return; } fail(); } public void testNonePredicateEx4() { try { PredicateUtils.nonePredicate((Collection) null); } catch (IllegalArgumentException ex) { return; } fail(); } public void testNonePredicateEx5() { try { PredicateUtils.nonePredicate(Collections.EMPTY_LIST); } catch (IllegalArgumentException ex) { return; } fail(); } public void testNonePredicateEx6() { try { Collection coll = new ArrayList(); coll.add(null); coll.add(null); PredicateUtils.nonePredicate(coll); } catch (IllegalArgumentException ex) { return; } fail(); } // instanceofPredicate //------------------------------------------------------------------ public void testInstanceOfPredicate() { assertNotNull(PredicateUtils.instanceofPredicate(String.class)); assertEquals(false, PredicateUtils.instanceofPredicate(String.class).evaluate(null)); // GenericsNote: Test no longer applicable. //assertEquals(false, PredicateUtils.instanceofPredicate(String.class).evaluate(cObject)); //assertEquals(false, PredicateUtils.instanceofPredicate(String.class).evaluate(cInteger)); assertEquals(true, PredicateUtils.instanceofPredicate(String.class).evaluate(cString)); } // uniquePredicate //------------------------------------------------------------------ public void testUniquePredicate() { Predicate p = PredicateUtils.uniquePredicate(); assertEquals(true, p.evaluate(new Object())); assertEquals(true, p.evaluate(new Object())); assertEquals(true, p.evaluate(new Object())); assertEquals(true, p.evaluate(cString)); assertEquals(false, p.evaluate(cString)); assertEquals(false, p.evaluate(cString)); } // asPredicate(Transformer) //------------------------------------------------------------------ public void testAsPredicateTransformer() { assertEquals(false, PredicateUtils.asPredicate(TransformerUtils.nopTransformer()).evaluate(Boolean.FALSE)); assertEquals(true, PredicateUtils.asPredicate(TransformerUtils.nopTransformer()).evaluate(Boolean.TRUE)); } public void testAsPredicateTransformerEx1() { try { PredicateUtils.asPredicate(null); } catch (IllegalArgumentException ex) { return; } fail(); } public void testAsPredicateTransformerEx2() { try { PredicateUtils.asPredicate(TransformerUtils.nopTransformer()).evaluate(null); } catch (FunctorException ex) { return; } fail(); } // invokerPredicate //------------------------------------------------------------------ public void testInvokerPredicate() { List list = new ArrayList(); assertEquals(true, PredicateUtils.invokerPredicate("isEmpty").evaluate(list)); list.add(new Object()); assertEquals(false, PredicateUtils.invokerPredicate("isEmpty").evaluate(list)); } public void testInvokerPredicateEx1() { try { PredicateUtils.invokerPredicate(null); } catch (IllegalArgumentException ex) { return; } fail(); } public void testInvokerPredicateEx2() { try { PredicateUtils.invokerPredicate("isEmpty").evaluate(null); } catch (FunctorException ex) { return; } fail(); } public void testInvokerPredicateEx3() { try { PredicateUtils.invokerPredicate("noSuchMethod").evaluate(new Object()); } catch (FunctorException ex) { return; } fail(); } // invokerPredicate2 //------------------------------------------------------------------ public void testInvokerPredicate2() { List list = new ArrayList(); assertEquals(false, PredicateUtils.invokerPredicate("contains", new Class[]{Object.class}, new Object[]{cString}).evaluate(list)); list.add(cString); assertEquals(true, PredicateUtils.invokerPredicate("contains", new Class[]{Object.class}, new Object[]{cString}).evaluate(list)); } public void testInvokerPredicate2Ex1() { try { PredicateUtils.invokerPredicate(null, null, null); } catch (IllegalArgumentException ex) { return; } fail(); } public void testInvokerPredicate2Ex2() { try { PredicateUtils.invokerPredicate("contains", new Class[]{Object.class}, new Object[]{cString}).evaluate(null); } catch (FunctorException ex) { return; } fail(); } public void testInvokerPredicate2Ex3() { try { PredicateUtils.invokerPredicate("noSuchMethod", new Class[]{Object.class}, new Object[]{cString}).evaluate(new Object()); } catch (FunctorException ex) { return; } fail(); } // nullIsException //------------------------------------------------------------------ public void testNullIsExceptionPredicate() { assertEquals(true, PredicateUtils.nullIsExceptionPredicate(PredicateUtils.truePredicate()).evaluate(new Object())); try { PredicateUtils.nullIsExceptionPredicate(PredicateUtils.truePredicate()).evaluate(null); } catch (FunctorException ex) { return; } fail(); } public void testNullIsExceptionPredicateEx1() { try { PredicateUtils.nullIsExceptionPredicate(null); } catch (IllegalArgumentException ex) { return; } fail(); } // nullIsTrue //------------------------------------------------------------------ public void testNullIsTruePredicate() { assertEquals(true, PredicateUtils.nullIsTruePredicate(PredicateUtils.truePredicate()).evaluate(null)); assertEquals(true, PredicateUtils.nullIsTruePredicate(PredicateUtils.truePredicate()).evaluate(new Object())); assertEquals(false, PredicateUtils.nullIsTruePredicate(PredicateUtils.falsePredicate()).evaluate(new Object())); } public void testNullIsTruePredicateEx1() { try { PredicateUtils.nullIsTruePredicate(null); } catch (IllegalArgumentException ex) { return; } fail(); } // nullIsFalse //------------------------------------------------------------------ public void testNullIsFalsePredicate() { assertEquals(false, PredicateUtils.nullIsFalsePredicate(PredicateUtils.truePredicate()).evaluate(null)); assertEquals(true, PredicateUtils.nullIsFalsePredicate(PredicateUtils.truePredicate()).evaluate(new Object())); assertEquals(false, PredicateUtils.nullIsFalsePredicate(PredicateUtils.falsePredicate()).evaluate(new Object())); } public void testNullIsFalsePredicateEx1() { try { PredicateUtils.nullIsFalsePredicate(null); } catch (IllegalArgumentException ex) { return; } fail(); } // transformed //------------------------------------------------------------------ public void testTransformedPredicate() { assertEquals(true, PredicateUtils.transformedPredicate(TransformerUtils.nopTransformer(), PredicateUtils.truePredicate()).evaluate(new Object())); Map map = new HashMap(); map.put(Boolean.TRUE, "Hello"); Transformer t = TransformerUtils.mapTransformer(map); Predicate p = PredicateUtils.equalPredicate("Hello"); assertEquals(false, PredicateUtils.transformedPredicate(t, p).evaluate(null)); assertEquals(true, PredicateUtils.transformedPredicate(t, p).evaluate(Boolean.TRUE)); try { PredicateUtils.transformedPredicate(null, null); fail(); } catch (IllegalArgumentException ex) { } } } collections-generic-4.01/src/test/org/apache/commons/collections15/overview.html0000644000175000017500000000317310464140763030256 0ustar giovannigiovanni

                  The Collections Test Framework is an extension to JUnit to enable quick and easy testing of collections.

                  Apache Jakarta Commons Collections Test Framework

                  The Collections Test Framework is an extension to JUnit to enable quick and easy testing of collections. The collections interfaces are large and complex to test thoroughly. These classes do most of the testing for you, and offer configuration by overriding methods when your collection bends the API. All you have to do is actually write the collection and make it pass.

                  The test framework does not depend on the main commons-collections jar file. The only exception to this are the Bag tests, but if you are testing this you must have the collections jar anyway.

                  NOTE: The test framework is released to aid developers. We will try to make changes backwards compatible. However, if necessary changes will be made to the test framework to improve the tests. collections-generic-4.01/src/test/org/apache/commons/collections15/list/0000755000175000017500000000000011664401370026466 5ustar giovannigiovannicollections-generic-4.01/src/test/org/apache/commons/collections15/list/TestPredicatedList.java0000644000175000017500000001147710464140762033105 0ustar giovannigiovanni/* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.list; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.collections15.Predicate; import org.apache.commons.collections15.PredicateUtils; import java.util.ArrayList; import java.util.List; /** * Extension of {@link TestList} for exercising the * {@link PredicatedList} implementation. * * @author Matt Hall, John Watkinson, Phil Steitz * @version $Revision: 1.1 $ $Date: 2005/10/11 19:11:58 $ * @since Commons Collections 3.0 */ public class TestPredicatedList extends AbstractTestList { public TestPredicatedList(String testName) { super(testName); } public static Test suite() { return new TestSuite(TestPredicatedList.class); } public static void main(String args[]) { String[] testCaseName = {TestPredicatedList.class.getName()}; junit.textui.TestRunner.main(testCaseName); } //------------------------------------------------------------------- protected Predicate truePredicate = PredicateUtils.truePredicate(); protected List decorateList(List list, Predicate predicate) { return PredicatedList.decorate(list, predicate); } public List makeEmptyList() { return decorateList(new ArrayList(), truePredicate); } public Object[] getFullElements() { return new Object[]{"1", "3", "5", "7", "2", "4", "6"}; } //-------------------------------------------------------------------- protected Predicate testPredicate = new Predicate() { public boolean evaluate(Object o) { return o instanceof String; } }; public List makeTestList() { return decorateList(new ArrayList(), testPredicate); } public void testIllegalAdd() { List list = makeTestList(); Integer i = new Integer(3); try { list.add(i); fail("Integer should fail string predicate."); } catch (IllegalArgumentException e) { // expected } assertTrue("Collection shouldn't contain illegal element", !list.contains(i)); } public void testIllegalAddAll() { List list = makeTestList(); List elements = new ArrayList(); elements.add("one"); elements.add("two"); elements.add(new Integer(3)); elements.add("four"); try { list.addAll(0, elements); fail("Integer should fail string predicate."); } catch (IllegalArgumentException e) { // expected } assertTrue("List shouldn't contain illegal element", !list.contains("one")); assertTrue("List shouldn't contain illegal element", !list.contains("two")); assertTrue("List shouldn't contain illegal element", !list.contains(new Integer(3))); assertTrue("List shouldn't contain illegal element", !list.contains("four")); } public void testIllegalSet() { List list = makeTestList(); try { list.set(0, new Integer(3)); fail("Integer should fail string predicate."); } catch (IllegalArgumentException e) { // expected } } public void testLegalAddAll() { List list = makeTestList(); list.add("zero"); List elements = new ArrayList(); elements.add("one"); elements.add("two"); elements.add("three"); list.addAll(1, elements); assertTrue("List should contain legal element", list.contains("zero")); assertTrue("List should contain legal element", list.contains("one")); assertTrue("List should contain legal element", list.contains("two")); assertTrue("List should contain legal element", list.contains("three")); } public String getCompatibilityVersion() { return "3.1"; } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk((java.io.Serializable) collection, "D:/dev/collections15/data/test/PredicatedList.emptyCollection.version3.1.obj"); // resetFull(); // writeExternalFormToDisk((java.io.Serializable) collection, "D:/dev/collections15/data/test/PredicatedList.fullCollection.version3.1.obj"); // } } collections-generic-4.01/src/test/org/apache/commons/collections15/list/TestTypedList.java0000644000175000017500000000347110464140760032117 0ustar giovannigiovanni/* * Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.list; import junit.framework.Test; import junit.framework.TestSuite; import java.util.ArrayList; import java.util.Collection; import java.util.List; /** * Extension of {@link TestList} for exercising the {@link TypedList} * implementation. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 19:11:58 $ * @since Commons Collections 3.1 */ public class TestTypedList extends AbstractTestList { public TestTypedList(String testName) { super(testName); } public static Test suite() { return new TestSuite(TestTypedList.class); } public static void main(String args[]) { String[] testCaseName = {TestTypedList.class.getName()}; junit.textui.TestRunner.main(testCaseName); } public Collection makeConfirmedCollection() { return new ArrayList(); } public List makeEmptyList() { return TypedList.decorate(new ArrayList(), Object.class); } public boolean isNullSupported() { return false; } public boolean skipSerializedCanonicalTests() { return true; // TypedList and PredicatedList get confused } } collections-generic-4.01/src/test/org/apache/commons/collections15/list/TestFixedSizeList.java0000644000175000017500000000453110464140762032724 0ustar giovannigiovanni/* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.list; import junit.framework.Test; import junit.framework.TestSuite; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * Extension of {@link TestList} for exercising the {@link FixedSizeList} * implementation. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 19:11:58 $ * @since Commons Collections 3.0 */ public class TestFixedSizeList extends AbstractTestList { public TestFixedSizeList(String testName) { super(testName); } public static Test suite() { return new TestSuite(TestFixedSizeList.class); } public static void main(String args[]) { String[] testCaseName = {TestFixedSizeList.class.getName()}; junit.textui.TestRunner.main(testCaseName); } public List makeEmptyList() { return FixedSizeList.decorate(new ArrayList()); } public List makeFullList() { List list = new ArrayList(); list.addAll(Arrays.asList(getFullElements())); return FixedSizeList.decorate(list); } public boolean isAddSupported() { return false; } public boolean isRemoveSupported() { return false; } public String getCompatibilityVersion() { return "3.1"; } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk((java.io.Serializable) collection, "D:/dev/collections15/data/test/FixedSizeList.emptyCollection.version3.1.obj"); // resetFull(); // writeExternalFormToDisk((java.io.Serializable) collection, "D:/dev/collections15/data/test/FixedSizeList.fullCollection.version3.1.obj"); // } } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootcollections-generic-4.01/src/test/org/apache/commons/collections15/list/TestCursorableLinkedList.javacollections-generic-4.01/src/test/org/apache/commons/collections15/list/TestCursorableLinkedList.jav0000644000175000017500000010612610464140763034125 0ustar giovannigiovanni/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.list; import junit.framework.Test; import org.apache.commons.collections15.BulkTest; import java.util.*; /** * Test class. * * @author Matt Hall, John Watkinson, Rodney Waldhoff * @author Simon Kitching * @version $Revision: 1.1 $ $Date: 2005/10/11 19:11:58 $ */ public class TestCursorableLinkedList extends TestAbstractLinkedList { public TestCursorableLinkedList(String testName) { super(testName); } public static Test suite() { return BulkTest.makeSuite(TestCursorableLinkedList.class); } public static void main(String args[]) { String[] testCaseName = {TestCursorableLinkedList.class.getName()}; junit.textui.TestRunner.main(testCaseName); } private CursorableLinkedList list = null; public void setUp() { list = new CursorableLinkedList(); } public List makeEmptyList() { return new CursorableLinkedList(); } public void testAdd() { assertEquals("[]", list.toString()); assertTrue(list.add(new Integer(1))); assertEquals("[1]", list.toString()); assertTrue(list.add(new Integer(2))); assertEquals("[1, 2]", list.toString()); assertTrue(list.add(new Integer(3))); assertEquals("[1, 2, 3]", list.toString()); assertTrue(list.addFirst(new Integer(0))); assertEquals("[0, 1, 2, 3]", list.toString()); assertTrue(list.addLast(new Integer(4))); assertEquals("[0, 1, 2, 3, 4]", list.toString()); list.add(0, new Integer(-2)); assertEquals("[-2, 0, 1, 2, 3, 4]", list.toString()); list.add(1, new Integer(-1)); assertEquals("[-2, -1, 0, 1, 2, 3, 4]", list.toString()); list.add(7, new Integer(5)); assertEquals("[-2, -1, 0, 1, 2, 3, 4, 5]", list.toString()); java.util.List list2 = new java.util.LinkedList(); list2.add("A"); list2.add("B"); list2.add("C"); assertTrue(list.addAll(list2)); assertEquals("[-2, -1, 0, 1, 2, 3, 4, 5, A, B, C]", list.toString()); assertTrue(list.addAll(3, list2)); assertEquals("[-2, -1, 0, A, B, C, 1, 2, 3, 4, 5, A, B, C]", list.toString()); } public void testClear() { assertEquals(0, list.size()); assertTrue(list.isEmpty()); list.clear(); assertEquals(0, list.size()); assertTrue(list.isEmpty()); list.add("element"); assertEquals(1, list.size()); assertTrue(!list.isEmpty()); list.clear(); assertEquals(0, list.size()); assertTrue(list.isEmpty()); list.add("element1"); list.add("element2"); assertEquals(2, list.size()); assertTrue(!list.isEmpty()); list.clear(); assertEquals(0, list.size()); assertTrue(list.isEmpty()); for (int i = 0; i < 1000; i++) { list.add(new Integer(i)); } assertEquals(1000, list.size()); assertTrue(!list.isEmpty()); list.clear(); assertEquals(0, list.size()); assertTrue(list.isEmpty()); } public void testContains() { assertTrue(!list.contains("A")); assertTrue(list.add("A")); assertTrue(list.contains("A")); assertTrue(list.add("B")); assertTrue(list.contains("A")); assertTrue(list.addFirst("a")); assertTrue(list.contains("A")); assertTrue(list.remove("a")); assertTrue(list.contains("A")); assertTrue(list.remove("A")); assertTrue(!list.contains("A")); } public void testContainsAll() { assertTrue(list.containsAll(list)); java.util.List list2 = new java.util.LinkedList(); assertTrue(list.containsAll(list2)); list2.add("A"); assertTrue(!list.containsAll(list2)); list.add("B"); list.add("A"); assertTrue(list.containsAll(list2)); list2.add("B"); assertTrue(list.containsAll(list2)); list2.add("C"); assertTrue(!list.containsAll(list2)); list.add("C"); assertTrue(list.containsAll(list2)); list2.add("C"); assertTrue(list.containsAll(list2)); assertTrue(list.containsAll(list)); } public void testCursorNavigation() { list.add("1"); list.add("2"); list.add("3"); list.add("4"); list.add("5"); CursorableLinkedList.Cursor it = list.cursor(); assertTrue(it.hasNext()); assertTrue(!it.hasPrevious()); assertEquals("1", it.next()); assertTrue(it.hasNext()); assertTrue(it.hasPrevious()); assertEquals("1", it.previous()); assertTrue(it.hasNext()); assertTrue(!it.hasPrevious()); assertEquals("1", it.next()); assertTrue(it.hasNext()); assertTrue(it.hasPrevious()); assertEquals("2", it.next()); assertTrue(it.hasNext()); assertTrue(it.hasPrevious()); assertEquals("2", it.previous()); assertTrue(it.hasNext()); assertTrue(it.hasPrevious()); assertEquals("2", it.next()); assertTrue(it.hasNext()); assertTrue(it.hasPrevious()); assertEquals("3", it.next()); assertTrue(it.hasNext()); assertTrue(it.hasPrevious()); assertEquals("4", it.next()); assertTrue(it.hasNext()); assertTrue(it.hasPrevious()); assertEquals("5", it.next()); assertTrue(!it.hasNext()); assertTrue(it.hasPrevious()); assertEquals("5", it.previous()); assertTrue(it.hasNext()); assertTrue(it.hasPrevious()); assertEquals("4", it.previous()); assertTrue(it.hasNext()); assertTrue(it.hasPrevious()); assertEquals("3", it.previous()); assertTrue(it.hasNext()); assertTrue(it.hasPrevious()); assertEquals("2", it.previous()); assertTrue(it.hasNext()); assertTrue(it.hasPrevious()); assertEquals("1", it.previous()); assertTrue(it.hasNext()); assertTrue(!it.hasPrevious()); it.close(); } public void testCursorSet() { list.add("1"); list.add("2"); list.add("3"); list.add("4"); list.add("5"); CursorableLinkedList.Cursor it = list.cursor(); assertEquals("1", it.next()); it.set("a"); assertEquals("a", it.previous()); it.set("A"); assertEquals("A", it.next()); assertEquals("2", it.next()); it.set("B"); assertEquals("3", it.next()); assertEquals("4", it.next()); it.set("D"); assertEquals("5", it.next()); it.set("E"); assertEquals("[A, B, 3, D, E]", list.toString()); it.close(); } public void testCursorRemove() { list.add("1"); list.add("2"); list.add("3"); list.add("4"); list.add("5"); CursorableLinkedList.Cursor it = list.cursor(); try { it.remove(); fail(); } catch (IllegalStateException e) { // expected } assertEquals("1", it.next()); assertEquals("2", it.next()); assertEquals("[1, 2, 3, 4, 5]", list.toString()); it.remove(); assertEquals("[1, 3, 4, 5]", list.toString()); assertEquals("3", it.next()); assertEquals("3", it.previous()); assertEquals("1", it.previous()); it.remove(); assertEquals("[3, 4, 5]", list.toString()); assertTrue(!it.hasPrevious()); assertEquals("3", it.next()); it.remove(); assertEquals("[4, 5]", list.toString()); try { it.remove(); } catch (IllegalStateException e) { // expected } assertEquals("4", it.next()); assertEquals("5", it.next()); it.remove(); assertEquals("[4]", list.toString()); assertEquals("4", it.previous()); it.remove(); assertEquals("[]", list.toString()); it.close(); } public void testCursorAdd() { CursorableLinkedList.Cursor it = list.cursor(); it.add("1"); assertEquals("[1]", list.toString()); it.add("3"); assertEquals("[1, 3]", list.toString()); it.add("5"); assertEquals("[1, 3, 5]", list.toString()); assertEquals("5", it.previous()); it.add("4"); assertEquals("[1, 3, 4, 5]", list.toString()); assertEquals("4", it.previous()); assertEquals("3", it.previous()); it.add("2"); assertEquals("[1, 2, 3, 4, 5]", list.toString()); it.close(); } public void testCursorConcurrentModification() { // this test verifies that cursors remain valid when the list // is modified via other means. list.add("1"); list.add("2"); list.add("3"); list.add("5"); list.add("7"); list.add("9"); CursorableLinkedList.Cursor c1 = list.cursor(); CursorableLinkedList.Cursor c2 = list.cursor(); Iterator li = list.iterator(); // test cursors remain valid when list modified by std Iterator // test cursors skip elements removed via ListIterator assertEquals("1", li.next()); assertEquals("2", li.next()); li.remove(); assertEquals("3", li.next()); assertEquals("1", c1.next()); assertEquals("3", c1.next()); assertEquals("1", c2.next()); // test cursor c1 can remove elements from previously modified list // test cursor c2 skips elements removed via different cursor c1.remove(); assertEquals("5", c2.next()); c2.add("6"); assertEquals("5", c1.next()); assertEquals("6", c1.next()); assertEquals("7", c1.next()); // test cursors remain valid when list mod via CursorableLinkedList // test cursor remains valid when elements inserted into list before // the current position of the cursor. list.add(0, "0"); // test cursor remains valid when element inserted immediately after // current element of a cursor, and the element is seen on the // next call to the next method of that cursor. list.add(5, "8"); assertEquals("8", c1.next()); assertEquals("9", c1.next()); c1.add("10"); assertEquals("7", c2.next()); assertEquals("8", c2.next()); assertEquals("9", c2.next()); assertEquals("10", c2.next()); try { c2.next(); fail(); } catch (NoSuchElementException nse) { } try { li.next(); fail(); } catch (ConcurrentModificationException cme) { } c1.close(); // not necessary c2.close(); // not necessary } public void testCursorNextIndexMid() { list.add("1"); list.add("2"); list.add("3"); list.add("5"); CursorableLinkedList.Cursor c1 = list.cursor(); Iterator li = list.iterator(); // test cursors remain valid when list modified by std Iterator // test cursors skip elements removed via ListIterator assertEquals("1", li.next()); assertEquals("2", li.next()); li.remove(); assertEquals(0, c1.nextIndex()); assertEquals("1", c1.next()); assertEquals(1, c1.nextIndex()); assertEquals("3", c1.next()); } public void testCursorNextIndexFirst() { list.add("1"); list.add("2"); list.add("3"); list.add("5"); CursorableLinkedList.Cursor c1 = list.cursor(); assertEquals(0, c1.nextIndex()); list.remove(0); assertEquals(0, c1.nextIndex()); assertEquals("2", c1.next()); assertEquals(1, c1.nextIndex()); assertEquals("3", c1.next()); } public void testCursorNextIndexAddBefore() { list.add("1"); list.add("2"); list.add("3"); list.add("5"); CursorableLinkedList.Cursor c1 = list.cursor(); assertEquals(0, c1.nextIndex()); assertEquals("1", c1.next()); list.add(0, "0"); assertEquals(2, c1.nextIndex()); assertEquals("2", c1.next()); } public void testCursorNextIndexAddNext() { list.add("1"); list.add("2"); list.add("3"); list.add("5"); CursorableLinkedList.Cursor c1 = list.cursor(); assertEquals(0, c1.nextIndex()); list.add(0, "0"); assertEquals(0, c1.nextIndex()); assertEquals("0", c1.next()); assertEquals(1, c1.nextIndex()); assertEquals("1", c1.next()); } public void testCursorNextIndexAddAfter() { list.add("1"); list.add("2"); list.add("3"); list.add("5"); CursorableLinkedList.Cursor c1 = list.cursor(); assertEquals(0, c1.nextIndex()); list.add(1, "0"); assertEquals(0, c1.nextIndex()); assertEquals("1", c1.next()); assertEquals(1, c1.nextIndex()); assertEquals("0", c1.next()); } public void testEqualsAndHashCode() { assertTrue(list.equals(list)); assertEquals(list.hashCode(), list.hashCode()); list.add("A"); assertTrue(list.equals(list)); assertEquals(list.hashCode(), list.hashCode()); CursorableLinkedList list2 = new CursorableLinkedList(); assertTrue(!list.equals(list2)); assertTrue(!list2.equals(list)); java.util.List list3 = new java.util.LinkedList(); assertTrue(!list.equals(list3)); assertTrue(!list3.equals(list)); assertTrue(list2.equals(list3)); assertTrue(list3.equals(list2)); assertEquals(list2.hashCode(), list3.hashCode()); list2.add("A"); assertTrue(list.equals(list2)); assertTrue(list2.equals(list)); assertTrue(!list2.equals(list3)); assertTrue(!list3.equals(list2)); list3.add("A"); assertTrue(list2.equals(list3)); assertTrue(list3.equals(list2)); assertEquals(list2.hashCode(), list3.hashCode()); list.add("B"); assertTrue(list.equals(list)); assertTrue(!list.equals(list2)); assertTrue(!list2.equals(list)); assertTrue(!list.equals(list3)); assertTrue(!list3.equals(list)); list2.add("B"); list3.add("B"); assertTrue(list.equals(list)); assertTrue(list.equals(list2)); assertTrue(list2.equals(list)); assertTrue(list2.equals(list3)); assertTrue(list3.equals(list2)); assertEquals(list2.hashCode(), list3.hashCode()); list.add("C"); list2.add("C"); list3.add("C"); assertTrue(list.equals(list)); assertTrue(list.equals(list2)); assertTrue(list2.equals(list)); assertTrue(list2.equals(list3)); assertTrue(list3.equals(list2)); assertEquals(list.hashCode(), list2.hashCode()); assertEquals(list2.hashCode(), list3.hashCode()); list.add("D"); list2.addFirst("D"); assertTrue(list.equals(list)); assertTrue(!list.equals(list2)); assertTrue(!list2.equals(list)); } public void testGet() { try { list.get(0); fail("shouldn't get here"); } catch (IndexOutOfBoundsException e) { // expected } assertTrue(list.add("A")); assertEquals("A", list.get(0)); assertTrue(list.add("B")); assertEquals("A", list.get(0)); assertEquals("B", list.get(1)); try { list.get(-1); fail("shouldn't get here"); } catch (IndexOutOfBoundsException e) { // expected } try { list.get(2); fail("shouldn't get here"); } catch (IndexOutOfBoundsException e) { // expected } } public void testIndexOf() { assertEquals(-1, list.indexOf("A")); assertEquals(-1, list.lastIndexOf("A")); list.add("A"); assertEquals(0, list.indexOf("A")); assertEquals(0, list.lastIndexOf("A")); assertEquals(-1, list.indexOf("B")); assertEquals(-1, list.lastIndexOf("B")); list.add("B"); assertEquals(0, list.indexOf("A")); assertEquals(0, list.lastIndexOf("A")); assertEquals(1, list.indexOf("B")); assertEquals(1, list.lastIndexOf("B")); list.addFirst("B"); assertEquals(1, list.indexOf("A")); assertEquals(1, list.lastIndexOf("A")); assertEquals(0, list.indexOf("B")); assertEquals(2, list.lastIndexOf("B")); } public void testIsEmpty() { assertTrue(list.isEmpty()); list.add("element"); assertTrue(!list.isEmpty()); list.remove("element"); assertTrue(list.isEmpty()); list.add("element"); assertTrue(!list.isEmpty()); list.clear(); assertTrue(list.isEmpty()); } public void testIterator() { list.add("1"); list.add("2"); list.add("3"); list.add("4"); list.add("5"); Iterator it = list.iterator(); assertTrue(it.hasNext()); assertEquals("1", it.next()); assertTrue(it.hasNext()); assertEquals("2", it.next()); assertTrue(it.hasNext()); assertEquals("3", it.next()); assertTrue(it.hasNext()); assertEquals("4", it.next()); assertTrue(it.hasNext()); assertEquals("5", it.next()); assertTrue(!it.hasNext()); it = list.iterator(); assertTrue(it.hasNext()); assertEquals("1", it.next()); it.remove(); assertEquals("[2, 3, 4, 5]", list.toString()); assertTrue(it.hasNext()); assertEquals("2", it.next()); it.remove(); assertEquals("[3, 4, 5]", list.toString()); assertTrue(it.hasNext()); assertEquals("3", it.next()); it.remove(); assertEquals("[4, 5]", list.toString()); assertTrue(it.hasNext()); assertEquals("4", it.next()); it.remove(); assertEquals("[5]", list.toString()); assertTrue(it.hasNext()); assertEquals("5", it.next()); it.remove(); assertEquals("[]", list.toString()); assertTrue(!it.hasNext()); } public void testListIteratorNavigation() { list.add("1"); list.add("2"); list.add("3"); list.add("4"); list.add("5"); ListIterator it = list.listIterator(); assertTrue(it.hasNext()); assertTrue(!it.hasPrevious()); assertEquals(-1, it.previousIndex()); assertEquals(0, it.nextIndex()); assertEquals("1", it.next()); assertTrue(it.hasNext()); assertTrue(it.hasPrevious()); assertEquals(0, it.previousIndex()); assertEquals(1, it.nextIndex()); assertEquals("1", it.previous()); assertTrue(it.hasNext()); assertTrue(!it.hasPrevious()); assertEquals(-1, it.previousIndex()); assertEquals(0, it.nextIndex()); assertEquals("1", it.next()); assertTrue(it.hasNext()); assertTrue(it.hasPrevious()); assertEquals(0, it.previousIndex()); assertEquals(1, it.nextIndex()); assertEquals("2", it.next()); assertTrue(it.hasNext()); assertTrue(it.hasPrevious()); assertEquals(1, it.previousIndex()); assertEquals(2, it.nextIndex()); assertEquals("2", it.previous()); assertTrue(it.hasNext()); assertTrue(it.hasPrevious()); assertEquals(0, it.previousIndex()); assertEquals(1, it.nextIndex()); assertEquals("2", it.next()); assertTrue(it.hasNext()); assertTrue(it.hasPrevious()); assertEquals(1, it.previousIndex()); assertEquals(2, it.nextIndex()); assertEquals("3", it.next()); assertTrue(it.hasNext()); assertTrue(it.hasPrevious()); assertEquals(2, it.previousIndex()); assertEquals(3, it.nextIndex()); assertEquals("4", it.next()); assertTrue(it.hasNext()); assertTrue(it.hasPrevious()); assertEquals(3, it.previousIndex()); assertEquals(4, it.nextIndex()); assertEquals("5", it.next()); assertTrue(!it.hasNext()); assertTrue(it.hasPrevious()); assertEquals(4, it.previousIndex()); assertEquals(5, it.nextIndex()); assertEquals("5", it.previous()); assertTrue(it.hasNext()); assertTrue(it.hasPrevious()); assertEquals(3, it.previousIndex()); assertEquals(4, it.nextIndex()); assertEquals("4", it.previous()); assertTrue(it.hasNext()); assertTrue(it.hasPrevious()); assertEquals(2, it.previousIndex()); assertEquals(3, it.nextIndex()); assertEquals("3", it.previous()); assertTrue(it.hasNext()); assertTrue(it.hasPrevious()); assertEquals(1, it.previousIndex()); assertEquals(2, it.nextIndex()); assertEquals("2", it.previous()); assertTrue(it.hasNext()); assertTrue(it.hasPrevious()); assertEquals(0, it.previousIndex()); assertEquals(1, it.nextIndex()); assertEquals("1", it.previous()); assertTrue(it.hasNext()); assertTrue(!it.hasPrevious()); assertEquals(-1, it.previousIndex()); assertEquals(0, it.nextIndex()); } public void testListIteratorSet() { list.add("1"); list.add("2"); list.add("3"); list.add("4"); list.add("5"); ListIterator it = list.listIterator(); assertEquals("1", it.next()); it.set("a"); assertEquals("a", it.previous()); it.set("A"); assertEquals("A", it.next()); assertEquals("2", it.next()); it.set("B"); assertEquals("3", it.next()); assertEquals("4", it.next()); it.set("D"); assertEquals("5", it.next()); it.set("E"); assertEquals("[A, B, 3, D, E]", list.toString()); } public void testListIteratorRemove() { list.add("1"); list.add("2"); list.add("3"); list.add("4"); list.add("5"); ListIterator it = list.listIterator(); try { it.remove(); } catch (IllegalStateException e) { // expected } assertEquals("1", it.next()); assertEquals("2", it.next()); assertEquals("[1, 2, 3, 4, 5]", list.toString()); it.remove(); assertEquals("[1, 3, 4, 5]", list.toString()); assertEquals("3", it.next()); assertEquals("3", it.previous()); assertEquals("1", it.previous()); it.remove(); assertEquals("[3, 4, 5]", list.toString()); assertTrue(!it.hasPrevious()); assertEquals("3", it.next()); it.remove(); assertEquals("[4, 5]", list.toString()); try { it.remove(); } catch (IllegalStateException e) { // expected } assertEquals("4", it.next()); assertEquals("5", it.next()); it.remove(); assertEquals("[4]", list.toString()); assertEquals("4", it.previous()); it.remove(); assertEquals("[]", list.toString()); } public void testListIteratorAdd() { ListIterator it = list.listIterator(); it.add("1"); assertEquals("[1]", list.toString()); it.add("3"); assertEquals("[1, 3]", list.toString()); it.add("5"); assertEquals("[1, 3, 5]", list.toString()); assertEquals("5", it.previous()); it.add("4"); assertEquals("[1, 3, 4, 5]", list.toString()); assertEquals("4", it.previous()); assertEquals("3", it.previous()); it.add("2"); assertEquals("[1, 2, 3, 4, 5]", list.toString()); } public void testRemoveAll() { list.add("1"); list.add("2"); list.add("3"); list.add("4"); list.add("5"); HashSet set = new HashSet(); set.add("A"); set.add("2"); set.add("C"); set.add("4"); set.add("D"); assertTrue(list.removeAll(set)); assertEquals("[1, 3, 5]", list.toString()); assertTrue(!list.removeAll(set)); } public void testRemoveByIndex() { list.add("1"); list.add("2"); list.add("3"); list.add("4"); list.add("5"); assertEquals("[1, 2, 3, 4, 5]", list.toString()); assertEquals("1", list.remove(0)); assertEquals("[2, 3, 4, 5]", list.toString()); assertEquals("3", list.remove(1)); assertEquals("[2, 4, 5]", list.toString()); assertEquals("4", list.remove(1)); assertEquals("[2, 5]", list.toString()); assertEquals("5", list.remove(1)); assertEquals("[2]", list.toString()); assertEquals("2", list.remove(0)); assertEquals("[]", list.toString()); } public void testRemove() { list.add("1"); list.add("1"); list.add("2"); list.add("3"); list.add("4"); list.add("5"); list.add("2"); list.add("3"); list.add("4"); list.add("5"); assertEquals("[1, 1, 2, 3, 4, 5, 2, 3, 4, 5]", list.toString()); assertTrue(!list.remove("6")); assertTrue(list.remove("5")); assertEquals("[1, 1, 2, 3, 4, 2, 3, 4, 5]", list.toString()); assertTrue(list.remove("5")); assertEquals("[1, 1, 2, 3, 4, 2, 3, 4]", list.toString()); assertTrue(!list.remove("5")); assertTrue(list.remove("1")); assertEquals("[1, 2, 3, 4, 2, 3, 4]", list.toString()); assertTrue(list.remove("1")); assertEquals("[2, 3, 4, 2, 3, 4]", list.toString()); assertTrue(list.remove("2")); assertEquals("[3, 4, 2, 3, 4]", list.toString()); assertTrue(list.remove("2")); assertEquals("[3, 4, 3, 4]", list.toString()); assertTrue(list.remove("3")); assertEquals("[4, 3, 4]", list.toString()); assertTrue(list.remove("3")); assertEquals("[4, 4]", list.toString()); assertTrue(list.remove("4")); assertEquals("[4]", list.toString()); assertTrue(list.remove("4")); assertEquals("[]", list.toString()); } public void testRetainAll() { list.add("1"); list.add("1"); list.add("2"); list.add("2"); list.add("3"); list.add("3"); list.add("4"); list.add("4"); list.add("5"); list.add("5"); HashSet set = new HashSet(); set.add("A"); set.add("2"); set.add("C"); set.add("4"); set.add("D"); assertTrue(list.retainAll(set)); assertEquals("[2, 2, 4, 4]", list.toString()); assertTrue(!list.retainAll(set)); } public void testSet() { list.add("1"); list.add("2"); list.add("3"); list.add("4"); list.add("5"); assertEquals("[1, 2, 3, 4, 5]", list.toString()); list.set(0, "A"); assertEquals("[A, 2, 3, 4, 5]", list.toString()); list.set(1, "B"); assertEquals("[A, B, 3, 4, 5]", list.toString()); list.set(2, "C"); assertEquals("[A, B, C, 4, 5]", list.toString()); list.set(3, "D"); assertEquals("[A, B, C, D, 5]", list.toString()); list.set(4, "E"); assertEquals("[A, B, C, D, E]", list.toString()); } public void testSubList() { list.add("A"); list.add("B"); list.add("C"); list.add("D"); list.add("E"); assertEquals("[A, B, C, D, E]", list.toString()); assertEquals("[A, B, C, D, E]", list.subList(0, 5).toString()); assertEquals("[B, C, D, E]", list.subList(1, 5).toString()); assertEquals("[C, D, E]", list.subList(2, 5).toString()); assertEquals("[D, E]", list.subList(3, 5).toString()); assertEquals("[E]", list.subList(4, 5).toString()); assertEquals("[]", list.subList(5, 5).toString()); } public void testSubListAddEnd() { list.add("A"); list.add("B"); list.add("C"); list.add("D"); list.add("E"); List sublist = list.subList(5, 5); sublist.add("F"); assertEquals("[A, B, C, D, E, F]", list.toString()); assertEquals("[F]", sublist.toString()); sublist.add("G"); assertEquals("[A, B, C, D, E, F, G]", list.toString()); assertEquals("[F, G]", sublist.toString()); } public void testSubListAddBegin() { list.add("A"); list.add("B"); list.add("C"); list.add("D"); list.add("E"); List sublist = list.subList(0, 0); sublist.add("a"); assertEquals("[a, A, B, C, D, E]", list.toString()); assertEquals("[a]", sublist.toString()); sublist.add("b"); assertEquals("[a, b, A, B, C, D, E]", list.toString()); assertEquals("[a, b]", sublist.toString()); } public void testSubListAddMiddle() { list.add("A"); list.add("B"); list.add("C"); list.add("D"); list.add("E"); List sublist = list.subList(1, 3); sublist.add("a"); assertEquals("[A, B, C, a, D, E]", list.toString()); assertEquals("[B, C, a]", sublist.toString()); sublist.add("b"); assertEquals("[A, B, C, a, b, D, E]", list.toString()); assertEquals("[B, C, a, b]", sublist.toString()); } public void testSubListRemove() { list.add("A"); list.add("B"); list.add("C"); list.add("D"); list.add("E"); List sublist = list.subList(1, 4); assertEquals("[B, C, D]", sublist.toString()); assertEquals("[A, B, C, D, E]", list.toString()); sublist.remove("C"); assertEquals("[B, D]", sublist.toString()); assertEquals("[A, B, D, E]", list.toString()); sublist.remove(1); assertEquals("[B]", sublist.toString()); assertEquals("[A, B, E]", list.toString()); sublist.clear(); assertEquals("[]", sublist.toString()); assertEquals("[A, E]", list.toString()); } public void testToArray() { list.add("1"); list.add("2"); list.add("3"); list.add("4"); list.add("5"); Object[] elts = list.toArray(); assertEquals("1", elts[0]); assertEquals("2", elts[1]); assertEquals("3", elts[2]); assertEquals("4", elts[3]); assertEquals("5", elts[4]); assertEquals(5, elts.length); String[] elts2 = (String[]) (list.toArray(new String[0])); assertEquals("1", elts2[0]); assertEquals("2", elts2[1]); assertEquals("3", elts2[2]); assertEquals("4", elts2[3]); assertEquals("5", elts2[4]); assertEquals(5, elts2.length); String[] elts3 = new String[5]; assertSame(elts3, list.toArray(elts3)); assertEquals("1", elts3[0]); assertEquals("2", elts3[1]); assertEquals("3", elts3[2]); assertEquals("4", elts3[3]); assertEquals("5", elts3[4]); assertEquals(5, elts3.length); String[] elts4 = new String[3]; String[] elts4b = (String[]) (list.toArray(elts4)); assertTrue(elts4 != elts4b); assertEquals("1", elts4b[0]); assertEquals("2", elts4b[1]); assertEquals("3", elts4b[2]); assertEquals("4", elts4b[3]); assertEquals("5", elts4b[4]); assertEquals(5, elts4b.length); } public void testSerialization() throws Exception { list.add("A"); list.add("B"); list.add("C"); list.add("D"); list.add("E"); java.io.ByteArrayOutputStream buf = new java.io.ByteArrayOutputStream(); java.io.ObjectOutputStream out = new java.io.ObjectOutputStream(buf); out.writeObject(list); out.flush(); out.close(); java.io.ByteArrayInputStream bufin = new java.io.ByteArrayInputStream(buf.toByteArray()); java.io.ObjectInputStream in = new java.io.ObjectInputStream(bufin); Object list2 = in.readObject(); assertTrue(list != list2); assertTrue(list2.equals(list)); assertTrue(list.equals(list2)); } public void testSerializationWithOpenCursor() throws Exception { list.add("A"); list.add("B"); list.add("C"); list.add("D"); list.add("E"); CursorableLinkedList.Cursor cursor = list.cursor(); java.io.ByteArrayOutputStream buf = new java.io.ByteArrayOutputStream(); java.io.ObjectOutputStream out = new java.io.ObjectOutputStream(buf); out.writeObject(list); out.flush(); out.close(); java.io.ByteArrayInputStream bufin = new java.io.ByteArrayInputStream(buf.toByteArray()); java.io.ObjectInputStream in = new java.io.ObjectInputStream(bufin); Object list2 = in.readObject(); assertTrue(list != list2); assertTrue(list2.equals(list)); assertTrue(list.equals(list2)); } public void testLongSerialization() throws Exception { // recursive serialization will cause a stack // overflow exception with long lists for (int i = 0; i < 10000; i++) { list.add(new Integer(i)); } java.io.ByteArrayOutputStream buf = new java.io.ByteArrayOutputStream(); java.io.ObjectOutputStream out = new java.io.ObjectOutputStream(buf); out.writeObject(list); out.flush(); out.close(); java.io.ByteArrayInputStream bufin = new java.io.ByteArrayInputStream(buf.toByteArray()); java.io.ObjectInputStream in = new java.io.ObjectInputStream(bufin); Object list2 = in.readObject(); assertTrue(list != list2); assertTrue(list2.equals(list)); assertTrue(list.equals(list2)); } /** * Ignore the serialization tests for sublists and sub-sublists. * * @return an array of sublist serialization test names */ public String[] ignoredTests() { ArrayList list = new ArrayList(); String prefix = "TestCursorableLinkedList"; String bulk = ".bulkTestSubList"; String[] ignored = new String[]{".testEmptyListSerialization", ".testFullListSerialization", ".testEmptyListCompatibility", ".testFullListCompatibility", ".testSimpleSerialization", ".testCanonicalEmptyCollectionExists", ".testCanonicalFullCollectionExists", ".testSerializeDeserializeThenCompare"}; for (int i = 0; i < ignored.length; i++) { list.add(prefix + bulk + ignored[i]); list.add(prefix + bulk + bulk + ignored[i]); } return (String[]) list.toArray(new String[0]); } } collections-generic-4.01/src/test/org/apache/commons/collections15/list/TestTreeList.java0000644000175000017500000001472710464140756031744 0ustar giovannigiovanni/* * Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.list; import junit.framework.Test; import org.apache.commons.collections15.BulkTest; import java.util.List; /** * JUnit tests * * @author Matt Hall, John Watkinson, Joerg Schmuecker * @version $Revision: 1.1 $ $Date: 2005/10/11 19:11:58 $ * @since Commons Collections 3.1 */ public class TestTreeList extends AbstractTestList { public TestTreeList(String name) { super(name); } public static void main(String[] args) { junit.textui.TestRunner.run(suite()); // System.out.println(" add; toArray; iterator; insert; get; indexOf; remove"); // System.out.print(" TreeList = "); // benchmark(new TreeList()); // System.out.print("\n ArrayList = "); // benchmark(new java.util.ArrayList()); // System.out.print("\n LinkedList = "); // benchmark(new java.util.LinkedList()); // benchmark(new NodeCachingLinkedList()); } public static Test suite() { return BulkTest.makeSuite(TestTreeList.class); } public static void benchmark(List l) { StringBuffer sb = new StringBuffer(); long start = System.currentTimeMillis(); for (int i = 0; i < 100000; i++) { l.add(new Integer(i)); } System.out.print(System.currentTimeMillis() - start + ";"); start = System.currentTimeMillis(); for (int i = 0; i < 200; i++) { l.toArray(); } System.out.print(System.currentTimeMillis() - start + ";"); start = System.currentTimeMillis(); for (int i = 0; i < 100; i++) { java.util.Iterator it = l.iterator(); while (it.hasNext()) { it.next(); } } System.out.print(System.currentTimeMillis() - start + ";"); start = System.currentTimeMillis(); for (int i = 0; i < 10000; i++) { int j = (int) (Math.random() * 100000); l.add(j, new Integer(-j)); } System.out.print(System.currentTimeMillis() - start + ";"); start = System.currentTimeMillis(); for (int i = 0; i < 50000; i++) { int j = (int) (Math.random() * 110000); l.get(j); } System.out.print(System.currentTimeMillis() - start + ";"); start = System.currentTimeMillis(); for (int i = 0; i < 200; i++) { int j = (int) (Math.random() * 100000); l.indexOf(new Integer(j)); } System.out.print(System.currentTimeMillis() - start + ";"); start = System.currentTimeMillis(); for (int i = 0; i < 10000; i++) { int j = (int) (Math.random() * 100000); l.remove(j); } System.out.print(System.currentTimeMillis() - start + ";"); } //----------------------------------------------------------------------- public List makeEmptyList() { return new TreeList(); } //----------------------------------------------------------------------- public void testAddMultiple() { List l = makeEmptyList(); l.add("hugo"); l.add("erna"); l.add("daniel"); l.add("andres"); l.add("harald"); l.add(0, null); assertEquals(null, l.get(0)); assertEquals("hugo", l.get(1)); assertEquals("erna", l.get(2)); assertEquals("daniel", l.get(3)); assertEquals("andres", l.get(4)); assertEquals("harald", l.get(5)); } public void testRemove() { List l = makeEmptyList(); l.add("hugo"); l.add("erna"); l.add("daniel"); l.add("andres"); l.add("harald"); l.add(0, null); int i = 0; assertEquals(null, l.get(i++)); assertEquals("hugo", l.get(i++)); assertEquals("erna", l.get(i++)); assertEquals("daniel", l.get(i++)); assertEquals("andres", l.get(i++)); assertEquals("harald", l.get(i++)); l.remove(0); i = 0; assertEquals("hugo", l.get(i++)); assertEquals("erna", l.get(i++)); assertEquals("daniel", l.get(i++)); assertEquals("andres", l.get(i++)); assertEquals("harald", l.get(i++)); i = 0; l.remove(1); assertEquals("hugo", l.get(i++)); assertEquals("daniel", l.get(i++)); assertEquals("andres", l.get(i++)); assertEquals("harald", l.get(i++)); i = 0; l.remove(2); assertEquals("hugo", l.get(i++)); assertEquals("daniel", l.get(i++)); assertEquals("harald", l.get(i++)); } public void testInsertBefore() { List l = makeEmptyList(); l.add("erna"); l.add(0, "hugo"); assertEquals("hugo", l.get(0)); assertEquals("erna", l.get(1)); } public void testIndexOf() { List l = makeEmptyList(); l.add("0"); l.add("1"); l.add("2"); l.add("3"); l.add("4"); l.add("5"); l.add("6"); assertEquals(0, l.indexOf("0")); assertEquals(1, l.indexOf("1")); assertEquals(2, l.indexOf("2")); assertEquals(3, l.indexOf("3")); assertEquals(4, l.indexOf("4")); assertEquals(5, l.indexOf("5")); assertEquals(6, l.indexOf("6")); l.set(1, "0"); assertEquals(0, l.indexOf("0")); l.set(3, "3"); assertEquals(3, l.indexOf("3")); l.set(2, "3"); assertEquals(2, l.indexOf("3")); l.set(1, "3"); assertEquals(1, l.indexOf("3")); l.set(0, "3"); assertEquals(0, l.indexOf("3")); } // public void testCheck() { // List l = makeEmptyList(); // l.add("A1"); // l.add("A2"); // l.add("A3"); // l.add("A4"); // l.add("A5"); // l.add("A6"); // } } collections-generic-4.01/src/test/org/apache/commons/collections15/list/TestSynchronizedList.java0000644000175000017500000000421710464140765033515 0ustar giovannigiovanni/* * Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.list; import junit.framework.Test; import junit.framework.TestSuite; import java.util.ArrayList; import java.util.Collection; import java.util.List; /** * Extension of {@link TestList} for exercising the {@link SynchronizedList} * implementation. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 19:11:58 $ * @since Commons Collections 3.1 */ public class TestSynchronizedList extends AbstractTestList { public TestSynchronizedList(String testName) { super(testName); } public static Test suite() { return new TestSuite(TestSynchronizedList.class); } public static void main(String args[]) { String[] testCaseName = {TestSynchronizedList.class.getName()}; junit.textui.TestRunner.main(testCaseName); } public Collection makeConfirmedCollection() { return new ArrayList(); } public List makeEmptyList() { return SynchronizedList.decorate(new ArrayList()); } public String getCompatibilityVersion() { return "3.1"; } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk((java.io.Serializable) collection, "D:/dev/collections15/data/test/SynchronizedList.emptyCollection.version3.1.obj"); // resetFull(); // writeExternalFormToDisk((java.io.Serializable) collection, "D:/dev/collections15/data/test/SynchronizedList.fullCollection.version3.1.obj"); // } } collections-generic-4.01/src/test/org/apache/commons/collections15/list/TestSetUniqueList.java0000644000175000017500000002074210464140765032761 0ustar giovannigiovanni/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.list; import junit.framework.Test; import junit.framework.TestSuite; import junit.textui.TestRunner; import java.util.*; /** * JUnit tests. * * @author Matt Hall, John Watkinson, Matthew Hawthorne * @version $Revision: 1.1 $ $Date: 2005/10/11 19:11:58 $ * @since Commons Collections 3.0 */ public class TestSetUniqueList extends AbstractTestList { public static void main(String[] args) { TestRunner.run(suite()); } public static Test suite() { return new TestSuite(TestSetUniqueList.class); } public TestSetUniqueList(String testName) { super(testName); } //----------------------------------------------------------------------- public List makeEmptyList() { return new SetUniqueList(new ArrayList(), new HashSet()); } public void testListIteratorSet() { // override to block resetFull(); ListIterator it = getList().listIterator(); it.next(); try { it.set(null); fail(); } catch (UnsupportedOperationException ex) { } } public Object[] getFullNonNullElements() { // override to avoid duplicate "One" return new Object[]{new String(""), new String("One"), new Integer(2), "Three", new Integer(4), new Double(5), new Float(6), "Seven", "Eight", new String("Nine"), new Integer(10), new Short((short) 11), new Long(12), "Thirteen", "14", "15", new Byte((byte) 16)}; } public void testListIteratorAdd() { // override to cope with Set behaviour resetEmpty(); List list1 = getList(); List list2 = getConfirmedList(); Object[] elements = getOtherElements(); // changed here ListIterator iter1 = list1.listIterator(); ListIterator iter2 = list2.listIterator(); for (int i = 0; i < elements.length; i++) { iter1.add(elements[i]); iter2.add(elements[i]); super.verify(); // changed here } resetFull(); iter1 = getList().listIterator(); iter2 = getConfirmedList().listIterator(); for (int i = 0; i < elements.length; i++) { iter1.next(); iter2.next(); iter1.add(elements[i]); iter2.add(elements[i]); super.verify(); // changed here } } public void testCollectionAddAll() { // override for set behaviour resetEmpty(); Object[] elements = getFullElements(); boolean r = collection.addAll(Arrays.asList(elements)); confirmed.addAll(Arrays.asList(elements)); verify(); assertTrue("Empty collection should change after addAll", r); for (int i = 0; i < elements.length; i++) { assertTrue("Collection should contain added element", collection.contains(elements[i])); } resetFull(); int size = collection.size(); elements = getOtherElements(); r = collection.addAll(Arrays.asList(elements)); confirmed.addAll(Arrays.asList(elements)); verify(); assertTrue("Full collection should change after addAll", r); for (int i = 0; i < elements.length; i++) { assertTrue("Full collection should contain added element " + i, collection.contains(elements[i])); } assertEquals("Size should increase after addAll", size + elements.length, collection.size()); } public void testListSetByIndex() { // override for set behaviour resetFull(); int size = collection.size(); getList().set(0, new Long(1000)); assertEquals(size, collection.size()); getList().set(2, new Long(1000)); assertEquals(size - 1, collection.size()); assertEquals(new Long(1000), getList().get(1)); // set into 2, but shifted down to 1 } boolean extraVerify = true; public void testCollectionIteratorRemove() { try { extraVerify = false; super.testCollectionIteratorRemove(); } finally { extraVerify = true; } } public void verify() { super.verify(); if (extraVerify) { int size = collection.size(); getList().add(new Long(1000)); assertEquals(size + 1, collection.size()); getList().add(new Long(1000)); assertEquals(size + 1, collection.size()); assertEquals(new Long(1000), getList().get(size)); getList().remove(size); } } //----------------------------------------------------------------------- public void testFactory() { Integer[] array = new Integer[]{new Integer(1), new Integer(2), new Integer(1)}; ArrayList list = new ArrayList(Arrays.asList(array)); final SetUniqueList lset = SetUniqueList.decorate(list); assertEquals("Duplicate element was added.", 2, lset.size()); assertEquals(new Integer(1), lset.get(0)); assertEquals(new Integer(2), lset.get(1)); assertEquals(new Integer(1), list.get(0)); assertEquals(new Integer(2), list.get(1)); } public void testAdd() { final SetUniqueList lset = new SetUniqueList(new ArrayList(), new HashSet()); // Duplicate element final Object obj = new Integer(1); lset.add(obj); lset.add(obj); assertEquals("Duplicate element was added.", 1, lset.size()); // Unique element lset.add(new Integer(2)); assertEquals("Unique element was not added.", 2, lset.size()); } public void testAddAll() { final SetUniqueList lset = new SetUniqueList(new ArrayList(), new HashSet()); lset.addAll(Arrays.asList(new Integer[]{new Integer(1), new Integer(1)})); assertEquals("Duplicate element was added.", 1, lset.size()); } public void testSet() { final SetUniqueList lset = new SetUniqueList(new ArrayList(), new HashSet()); // Duplicate element final Object obj1 = new Integer(1); final Object obj2 = new Integer(2); final Object obj3 = new Integer(3); lset.add(obj1); lset.add(obj2); lset.set(0, obj1); assertEquals(2, lset.size()); assertSame(obj1, lset.get(0)); assertSame(obj2, lset.get(1)); lset.clear(); lset.add(obj1); lset.add(obj2); lset.set(0, obj2); assertEquals(1, lset.size()); assertSame(obj2, lset.get(0)); lset.clear(); lset.add(obj1); lset.add(obj2); lset.set(0, obj3); assertEquals(2, lset.size()); assertSame(obj3, lset.get(0)); assertSame(obj2, lset.get(1)); lset.clear(); lset.add(obj1); lset.add(obj2); lset.set(1, obj1); assertEquals(1, lset.size()); assertSame(obj1, lset.get(0)); } public void testListIterator() { final SetUniqueList lset = new SetUniqueList(new ArrayList(), new HashSet()); final Object obj1 = new Integer(1); final Object obj2 = new Integer(2); lset.add(obj1); lset.add(obj2); // Attempts to add a duplicate object for (final ListIterator it = lset.listIterator(); it.hasNext();) { it.next(); if (!it.hasNext()) { it.add(obj1); break; } } assertEquals("Duplicate element was added", 2, lset.size()); } public String getCompatibilityVersion() { return "3.1"; } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk((java.io.Serializable) collection, "D:/dev/collections15/data/test/SetUniqueList.emptyCollection.version3.1.obj"); // resetFull(); // writeExternalFormToDisk((java.io.Serializable) collection, "D:/dev/collections15/data/test/SetUniqueList.fullCollection.version3.1.obj"); // } } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootcollections-generic-4.01/src/test/org/apache/commons/collections15/list/TestNodeCachingLinkedList.javacollections-generic-4.01/src/test/org/apache/commons/collections15/list/TestNodeCachingLinkedList.ja0000644000175000017500000001217310464140764033777 0ustar giovannigiovanni/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.list; import junit.framework.Test; import org.apache.commons.collections15.BulkTest; import java.util.Arrays; import java.util.LinkedList; import java.util.List; /** * Test class for NodeCachingLinkedList, a performance optimised LinkedList. * * @author Jeff Varszegi * @author Matt Hall, John Watkinson, Phil Steitz * @version $Revision: 1.1 $ $Date: 2005/10/11 19:11:58 $ */ public class TestNodeCachingLinkedList extends TestAbstractLinkedList { public TestNodeCachingLinkedList(String testName) { super(testName); } public static void main(String args[]) { compareSpeed(); String[] testCaseName = {TestNodeCachingLinkedList.class.getName()}; junit.textui.TestRunner.main(testCaseName); } public static Test suite() { return BulkTest.makeSuite(TestNodeCachingLinkedList.class); } //----------------------------------------------------------------------- public List makeEmptyList() { return new NodeCachingLinkedList(); } public String getCompatibilityVersion() { return "3"; } //----------------------------------------------------------------------- public void testShrinkCache() { if (isRemoveSupported() == false || isAddSupported() == false) return; resetEmpty(); NodeCachingLinkedList list = (NodeCachingLinkedList) collection; list.addAll(Arrays.asList(new String[]{"1", "2", "3", "4"})); list.removeAllNodes(); // Will dump all 4 elements into cache ((NodeCachingLinkedList) list).setMaximumCacheSize(2); // shrink cache list.addAll(Arrays.asList(new String[]{"1", "2", "3", "4"})); checkNodes(); list.removeNode(list.getNode(0, false)); // no room in cache list.removeNode(list.getNode(0, false)); list.removeNode(list.getNode(0, false)); checkNodes(); list.addAll(Arrays.asList(new String[]{"1", "2", "3", "4"})); checkNodes(); } //----------------------------------------------------------------------- public static void compareSpeed() { NodeCachingLinkedList ncll = new NodeCachingLinkedList(); LinkedList ll = new LinkedList(); Object o1 = new Object(); Object o2 = new Object(); int loopCount = 4000000; long startTime, endTime; System.out.println("Testing relative execution time of commonly-used methods..."); startTime = System.currentTimeMillis(); for (int x = loopCount; x > 0; x--) { // unrolled a few times to minimize effect of loop ll.addFirst(o1); ll.addLast(o2); ll.removeFirst(); ll.removeLast(); ll.add(o1); ll.remove(0); // ll.addFirst(o1); ll.addLast(o2); ll.removeFirst(); ll.removeLast(); ll.add(o1); ll.remove(0); // ll.addFirst(o1); ll.addLast(o2); ll.removeFirst(); ll.removeLast(); ll.add(o1); ll.remove(0); } endTime = System.currentTimeMillis(); System.out.println("Time with LinkedList: " + (endTime - startTime) + " ms"); startTime = System.currentTimeMillis(); for (int x = loopCount; x > 0; x--) { ncll.addFirst(o1); ncll.addLast(o2); ncll.removeFirst(); ncll.removeLast(); ncll.add(o1); ncll.remove(0); // ncll.addFirst(o1); ncll.addLast(o2); ncll.removeFirst(); ncll.removeLast(); ncll.add(o1); ncll.remove(0); // ncll.addFirst(o1); ncll.addLast(o2); ncll.removeFirst(); ncll.removeLast(); ncll.add(o1); ncll.remove(0); } endTime = System.currentTimeMillis(); System.out.println("Time with NodeCachingLinkedList: " + (endTime - startTime) + " ms"); } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk((java.io.Serializable) collection, // "D:/dev/collections15/data/test/NodeCachingLinkedList.emptyCollection.version3.obj"); // resetFull(); // writeExternalFormToDisk((java.io.Serializable) collection, // "D:/dev/collections15/data/test/NodeCachingLinkedList.fullCollection.version3.obj"); // } } collections-generic-4.01/src/test/org/apache/commons/collections15/list/TestAbstractLinkedList.java0000644000175000017500000001434110464140763033725 0ustar giovannigiovanni/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.list; import java.util.Arrays; /** * Test case for {@link AbstractLinkedList}. * * @author Rich Dougherty * @author David Hay * @author Matt Hall, John Watkinson, Phil Steitz * @version $Revision: 1.1 $ $Date: 2005/10/11 19:11:58 $ */ public abstract class TestAbstractLinkedList extends AbstractTestList { public TestAbstractLinkedList(String testName) { super(testName); } //----------------------------------------------------------------------- public void testRemoveFirst() { resetEmpty(); AbstractLinkedList list = (AbstractLinkedList) collection; if (isRemoveSupported() == false) { try { list.removeFirst(); } catch (UnsupportedOperationException ex) { } } list.addAll(Arrays.asList(new String[]{"value1", "value2"})); assertEquals("value1", list.removeFirst()); checkNodes(); list.addLast("value3"); checkNodes(); assertEquals("value2", list.removeFirst()); assertEquals("value3", list.removeFirst()); checkNodes(); list.addLast("value4"); checkNodes(); assertEquals("value4", list.removeFirst()); checkNodes(); } public void testRemoveLast() { resetEmpty(); AbstractLinkedList list = (AbstractLinkedList) collection; if (isRemoveSupported() == false) { try { list.removeLast(); } catch (UnsupportedOperationException ex) { } } list.addAll(Arrays.asList(new String[]{"value1", "value2"})); assertEquals("value2", list.removeLast()); list.addFirst("value3"); checkNodes(); assertEquals("value1", list.removeLast()); assertEquals("value3", list.removeLast()); list.addFirst("value4"); checkNodes(); assertEquals("value4", list.removeFirst()); } public void testAddNodeAfter() { resetEmpty(); AbstractLinkedList list = (AbstractLinkedList) collection; if (isAddSupported() == false) { try { list.addFirst(null); } catch (UnsupportedOperationException ex) { } } list.addFirst("value1"); list.addNodeAfter(list.getNode(0, false), "value2"); assertEquals("value1", list.getFirst()); assertEquals("value2", list.getLast()); list.removeFirst(); checkNodes(); list.addNodeAfter(list.getNode(0, false), "value3"); checkNodes(); assertEquals("value2", list.getFirst()); assertEquals("value3", list.getLast()); list.addNodeAfter(list.getNode(0, false), "value4"); checkNodes(); assertEquals("value2", list.getFirst()); assertEquals("value3", list.getLast()); assertEquals("value4", list.get(1)); list.addNodeAfter(list.getNode(2, false), "value5"); checkNodes(); assertEquals("value2", list.getFirst()); assertEquals("value4", list.get(1)); assertEquals("value3", list.get(2)); assertEquals("value5", list.getLast()); } public void testRemoveNode() { resetEmpty(); if (isAddSupported() == false || isRemoveSupported() == false) return; AbstractLinkedList list = (AbstractLinkedList) collection; list.addAll(Arrays.asList(new String[]{"value1", "value2"})); list.removeNode(list.getNode(0, false)); checkNodes(); assertEquals("value2", list.getFirst()); assertEquals("value2", list.getLast()); list.addFirst("value1"); list.addFirst("value0"); checkNodes(); list.removeNode(list.getNode(1, false)); assertEquals("value0", list.getFirst()); assertEquals("value2", list.getLast()); checkNodes(); list.removeNode(list.getNode(1, false)); assertEquals("value0", list.getFirst()); assertEquals("value0", list.getLast()); checkNodes(); } public void testGetNode() { resetEmpty(); AbstractLinkedList list = (AbstractLinkedList) collection; // get marker assertEquals(list.getNode(0, true).previous, list.getNode(0, true).next); try { Object obj = list.getNode(0, false); fail("Expecting IndexOutOfBoundsException."); } catch (IndexOutOfBoundsException ex) { // expected } list.addAll(Arrays.asList(new String[]{"value1", "value2"})); checkNodes(); list.addFirst("value0"); checkNodes(); list.removeNode(list.getNode(1, false)); checkNodes(); try { Object obj = list.getNode(2, false); fail("Expecting IndexOutOfBoundsException."); } catch (IndexOutOfBoundsException ex) { // expected } try { Object obj = list.getNode(-1, false); fail("Expecting IndexOutOfBoundsException."); } catch (IndexOutOfBoundsException ex) { // expected } try { Object obj = list.getNode(3, true); fail("Expecting IndexOutOfBoundsException."); } catch (IndexOutOfBoundsException ex) { // expected } } protected void checkNodes() { AbstractLinkedList list = (AbstractLinkedList) collection; for (int i = 0; i < list.size; i++) { assertEquals(list.getNode(i, false).next, list.getNode(i + 1, true)); if (i < list.size - 1) { assertEquals(list.getNode(i + 1, false).previous, list.getNode(i, false)); } } } } collections-generic-4.01/src/test/org/apache/commons/collections15/list/AbstractTestList.java0000644000175000017500000011437510464140755032607 0ustar giovannigiovanni/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.list; import org.apache.commons.collections15.BulkTest; import org.apache.commons.collections15.collection.AbstractTestCollection; import org.apache.commons.collections15.iterators.AbstractTestListIterator; import java.io.IOException; import java.io.Serializable; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.*; /** * Abstract test class for {@link java.util.List} methods and contracts. *

                  * To use, simply extend this class, and implement * the {@link #makeEmptyList} method. *

                  * If your {@link List} fails one of these tests by design, * you may still use this base set of cases. Simply override the * test case (method) your {@link List} fails or override one of the * protected methods from AbstractTestCollection. * * @author Rodney Waldhoff * @author Paul Jack * @author Stephen Colebourne * @author Matt Hall, John Watkinson, Neil O'Toole * @version $Revision: 1.1 $ $Date: 2005/10/11 19:11:58 $ */ public abstract class AbstractTestList extends AbstractTestCollection { /** * JUnit constructor. * * @param testName the test class name */ public AbstractTestList(String testName) { super(testName); } //----------------------------------------------------------------------- /** * Returns true if the collections15 produced by * {@link #makeCollection()} and {@link #makeFullCollection()} * support the set operation.

                  * Default implementation returns true. Override if your collection * class does not support set. */ public boolean isSetSupported() { return true; } //----------------------------------------------------------------------- /** * Verifies that the test list implementation matches the confirmed list * implementation. */ public void verify() { super.verify(); List list1 = getList(); List list2 = getConfirmedList(); assertEquals("List should equal confirmed", list1, list2); assertEquals("Confirmed should equal list", list2, list1); assertEquals("Hash codes should be equal", list1.hashCode(), list2.hashCode()); int i = 0; Iterator iterator1 = list1.iterator(); Iterator iterator2 = list2.iterator(); Object[] array = list1.toArray(); while (iterator2.hasNext()) { assertTrue("List iterator should have next", iterator1.hasNext()); Object o1 = iterator1.next(); Object o2 = iterator2.next(); assertEquals("Iterator elements should be equal", o1, o2); o2 = list1.get(i); assertEquals("get should return correct element", o1, o2); o2 = array[i]; assertEquals("toArray should have correct element", o1, o2); i++; } } //----------------------------------------------------------------------- /** * List equals method is defined. */ public boolean isEqualsCheckable() { return true; } /** * Returns an empty {@link ArrayList}. */ public Collection makeConfirmedCollection() { ArrayList list = new ArrayList(); return list; } /** * Returns a full {@link ArrayList}. */ public Collection makeConfirmedFullCollection() { ArrayList list = new ArrayList(); list.addAll(Arrays.asList(getFullElements())); return list; } /** * Return a new, empty {@link List} to be used for testing. * * @return an empty list for testing. */ public abstract List makeEmptyList(); /** * Return a new, full {@link List} to be used for testing. * * @return a full list for testing */ public List makeFullList() { // only works if list supports optional "addAll(Collection)" List list = makeEmptyList(); list.addAll(Arrays.asList(getFullElements())); return list; } /** * Returns {@link #makeEmptyList()}. * * @return an empty list to be used for testing */ public final Collection makeCollection() { return makeEmptyList(); } /** * Returns {@link #makeFullList()}. * * @return a full list to be used for testing */ public final Collection makeFullCollection() { return makeFullList(); } //----------------------------------------------------------------------- /** * Returns the {@link #collection} field cast to a {@link List}. * * @return the collection field as a List */ public List getList() { return (List) collection; } /** * Returns the {@link #confirmed} field cast to a {@link List}. * * @return the confirmed field as a List */ public List getConfirmedList() { return (List) confirmed; } //----------------------------------------------------------------------- /** * Tests bounds checking for {@link List#add(int, Object)} on an * empty list. */ public void testListAddByIndexBoundsChecking() { if (!isAddSupported()) { return; } List list; Object element = getOtherElements()[0]; try { list = makeEmptyList(); list.add(Integer.MIN_VALUE, element); fail("List.add should throw IndexOutOfBoundsException [Integer.MIN_VALUE]"); } catch (IndexOutOfBoundsException e) { // expected } try { list = makeEmptyList(); list.add(-1, element); fail("List.add should throw IndexOutOfBoundsException [-1]"); } catch (IndexOutOfBoundsException e) { // expected } try { list = makeEmptyList(); list.add(1, element); fail("List.add should throw IndexOutOfBoundsException [1]"); } catch (IndexOutOfBoundsException e) { // expected } try { list = makeEmptyList(); list.add(Integer.MAX_VALUE, element); fail("List.add should throw IndexOutOfBoundsException [Integer.MAX_VALUE]"); } catch (IndexOutOfBoundsException e) { // expected } } /** * Tests bounds checking for {@link List#add(int, Object)} on a * full list. */ public void testListAddByIndexBoundsChecking2() { if (!isAddSupported()) { return; } List list; Object element = getOtherElements()[0]; try { list = makeFullList(); list.add(Integer.MIN_VALUE, element); fail("List.add should throw IndexOutOfBoundsException [Integer.MIN_VALUE]"); } catch (IndexOutOfBoundsException e) { // expected } try { list = makeFullList(); list.add(-1, element); fail("List.add should throw IndexOutOfBoundsException [-1]"); } catch (IndexOutOfBoundsException e) { // expected } try { list = makeFullList(); list.add(list.size() + 1, element); fail("List.add should throw IndexOutOfBoundsException [size + 1]"); } catch (IndexOutOfBoundsException e) { // expected } try { list = makeFullList(); list.add(Integer.MAX_VALUE, element); fail("List.add should throw IndexOutOfBoundsException [Integer.MAX_VALUE]"); } catch (IndexOutOfBoundsException e) { // expected } } /** * Tests {@link List#add(int,Object)}. */ public void testListAddByIndex() { if (!isAddSupported()) { return; } Object element = getOtherElements()[0]; int max = getFullElements().length; for (int i = 0; i <= max; i++) { resetFull(); ((List) collection).add(i, element); ((List) confirmed).add(i, element); verify(); } } /** * Tests {@link List#equals(Object)}. */ public void testListEquals() { resetEmpty(); List list = getList(); assertEquals("Empty lists should be equal", true, list.equals(confirmed)); verify(); assertEquals("Empty list should equal self", true, list.equals(list)); verify(); List list2 = Arrays.asList(getFullElements()); assertEquals("Empty list shouldn't equal full", false, list.equals(list2)); verify(); list2 = Arrays.asList(getOtherElements()); assertEquals("Empty list shouldn't equal other", false, list.equals(list2)); verify(); resetFull(); list = getList(); assertEquals("Full lists should be equal", true, list.equals(confirmed)); verify(); assertEquals("Full list should equal self", true, list.equals(list)); verify(); list2 = makeEmptyList(); assertEquals("Full list shouldn't equal empty", false, list.equals(list2)); verify(); list2 = Arrays.asList(getOtherElements()); assertEquals("Full list shouldn't equal other", false, list.equals(list2)); verify(); list2 = Arrays.asList(getFullElements()); if (list2.size() < 2 && isAddSupported()) { // main list is only size 1, so lets add other elements to get a better list list.addAll(Arrays.asList(getOtherElements())); confirmed.addAll(Arrays.asList(getOtherElements())); list2 = new ArrayList(list2); list2.addAll(Arrays.asList(getOtherElements())); } if (list2.size() > 1) { Collections.reverse(list2); assertEquals("Full list shouldn't equal full list with same elements but different order", false, list.equals(list2)); verify(); } resetFull(); list = getList(); assertEquals("List shouldn't equal String", false, list.equals("")); verify(); final List listForC = Arrays.asList(getFullElements()); Collection c = new AbstractCollection() { public int size() { return listForC.size(); } public Iterator iterator() { return listForC.iterator(); } }; assertEquals("List shouldn't equal nonlist with same elements in same order", false, list.equals(c)); verify(); } /** * Tests {@link List#hashCode()}. */ public void testListHashCode() { resetEmpty(); int hash1 = collection.hashCode(); int hash2 = confirmed.hashCode(); assertEquals("Empty lists should have equal hashCodes", hash1, hash2); verify(); resetFull(); hash1 = collection.hashCode(); hash2 = confirmed.hashCode(); assertEquals("Full lists should have equal hashCodes", hash1, hash2); verify(); } /** * Tests {@link List#get(int)}. */ public void testListGetByIndex() { resetFull(); List list = getList(); Object[] elements = getFullElements(); for (int i = 0; i < elements.length; i++) { assertEquals("List should contain correct elements", elements[i], list.get(i)); verify(); } } /** * Tests bounds checking for {@link List#get(int)} on an * empty list. */ public void testListGetByIndexBoundsChecking() { List list = makeEmptyList(); try { list.get(Integer.MIN_VALUE); fail("List.get should throw IndexOutOfBoundsException [Integer.MIN_VALUE]"); } catch (IndexOutOfBoundsException e) { // expected } try { list.get(-1); fail("List.get should throw IndexOutOfBoundsException [-1]"); } catch (IndexOutOfBoundsException e) { // expected } try { list.get(0); fail("List.get should throw IndexOutOfBoundsException [0]"); } catch (IndexOutOfBoundsException e) { // expected } try { list.get(1); fail("List.get should throw IndexOutOfBoundsException [1]"); } catch (IndexOutOfBoundsException e) { // expected } try { list.get(Integer.MAX_VALUE); fail("List.get should throw IndexOutOfBoundsException [Integer.MAX_VALUE]"); } catch (IndexOutOfBoundsException e) { // expected } } /** * Tests bounds checking for {@link List#get(int)} on a * full list. */ public void testListGetByIndexBoundsChecking2() { List list = makeFullList(); try { list.get(Integer.MIN_VALUE); fail("List.get should throw IndexOutOfBoundsException [Integer.MIN_VALUE]"); } catch (IndexOutOfBoundsException e) { // expected } try { list.get(-1); fail("List.get should throw IndexOutOfBoundsException [-1]"); } catch (IndexOutOfBoundsException e) { // expected } try { list.get(getFullElements().length); fail("List.get should throw IndexOutOfBoundsException [size]"); } catch (IndexOutOfBoundsException e) { // expected } try { list.get(Integer.MAX_VALUE); fail("List.get should throw IndexOutOfBoundsException [Integer.MAX_VALUE]"); } catch (IndexOutOfBoundsException e) { // expected } } /** * Tests {@link List#indexOf}. */ public void testListIndexOf() { resetFull(); List list1 = getList(); List list2 = getConfirmedList(); Iterator iterator = list2.iterator(); while (iterator.hasNext()) { Object element = iterator.next(); assertEquals("indexOf should return correct result", list1.indexOf(element), list2.indexOf(element)); verify(); } Object[] other = getOtherElements(); for (int i = 0; i < other.length; i++) { assertEquals("indexOf should return -1 for nonexistent element", list1.indexOf(other[i]), -1); verify(); } } /** * Tests {@link List#lastIndexOf}. */ public void testListLastIndexOf() { resetFull(); List list1 = getList(); List list2 = getConfirmedList(); Iterator iterator = list2.iterator(); while (iterator.hasNext()) { Object element = iterator.next(); assertEquals("lastIndexOf should return correct result", list1.lastIndexOf(element), list2.lastIndexOf(element)); verify(); } Object[] other = getOtherElements(); for (int i = 0; i < other.length; i++) { assertEquals("lastIndexOf should return -1 for nonexistent " + "element", list1.lastIndexOf(other[i]), -1); verify(); } } /** * Tests bounds checking for {@link List#set(int,Object)} on an * empty list. */ public void testListSetByIndexBoundsChecking() { if (!isSetSupported()) { return; } List list = makeEmptyList(); Object element = getOtherElements()[0]; try { list.set(Integer.MIN_VALUE, element); fail("List.set should throw IndexOutOfBoundsException [Integer.MIN_VALUE]"); } catch (IndexOutOfBoundsException e) { // expected } try { list.set(-1, element); fail("List.set should throw IndexOutOfBoundsException [-1]"); } catch (IndexOutOfBoundsException e) { // expected } try { list.set(0, element); fail("List.set should throw IndexOutOfBoundsException [0]"); } catch (IndexOutOfBoundsException e) { // expected } try { list.set(1, element); fail("List.set should throw IndexOutOfBoundsException [1]"); } catch (IndexOutOfBoundsException e) { // expected } try { list.set(Integer.MAX_VALUE, element); fail("List.set should throw IndexOutOfBoundsException [Integer.MAX_VALUE]"); } catch (IndexOutOfBoundsException e) { // expected } } /** * Tests bounds checking for {@link List#set(int,Object)} on a * full list. */ public void testListSetByIndexBoundsChecking2() { if (!isSetSupported()) return; List list = makeFullList(); Object element = getOtherElements()[0]; try { list.set(Integer.MIN_VALUE, element); fail("List.set should throw IndexOutOfBoundsException " + "[Integer.MIN_VALUE]"); } catch (IndexOutOfBoundsException e) { // expected } try { list.set(-1, element); fail("List.set should throw IndexOutOfBoundsException [-1]"); } catch (IndexOutOfBoundsException e) { // expected } try { list.set(getFullElements().length, element); fail("List.set should throw IndexOutOfBoundsException [size]"); } catch (IndexOutOfBoundsException e) { // expected } try { list.set(Integer.MAX_VALUE, element); fail("List.set should throw IndexOutOfBoundsException " + "[Integer.MAX_VALUE]"); } catch (IndexOutOfBoundsException e) { // expected } } /** * Test {@link List#set(int,Object)}. */ public void testListSetByIndex() { if (!isSetSupported()) return; resetFull(); Object[] elements = getFullElements(); Object[] other = getOtherElements(); for (int i = 0; i < elements.length; i++) { Object n = other[i % other.length]; Object v = ((List) collection).set(i, n); assertEquals("Set should return correct element", elements[i], v); ((List) confirmed).set(i, n); verify(); } } /** * If {@link #isSetSupported()} returns false, tests that set operation * raises UnsupportedOperationException. */ public void testUnsupportedSet() { if (isSetSupported()) return; resetFull(); try { ((List) collection).set(0, new Object()); fail("Emtpy collection should not support set."); } catch (UnsupportedOperationException e) { // expected } // make sure things didn't change even if the expected exception was // thrown. verify(); } /** * Tests bounds checking for {@link List#remove(int)} on an * empty list. */ public void testListRemoveByIndexBoundsChecking() { if (!isRemoveSupported()) return; List list = makeEmptyList(); try { list.remove(Integer.MIN_VALUE); fail("List.remove should throw IndexOutOfBoundsException " + "[Integer.MIN_VALUE]"); } catch (IndexOutOfBoundsException e) { // expected } try { list.remove(-1); fail("List.remove should throw IndexOutOfBoundsException [-1]"); } catch (IndexOutOfBoundsException e) { // expected } try { list.remove(0); fail("List.remove should throw IndexOutOfBoundsException [0]"); } catch (IndexOutOfBoundsException e) { // expected } try { list.remove(1); fail("List.remove should throw IndexOutOfBoundsException [1]"); } catch (IndexOutOfBoundsException e) { // expected } try { list.remove(Integer.MAX_VALUE); fail("List.remove should throw IndexOutOfBoundsException " + "[Integer.MAX_VALUE]"); } catch (IndexOutOfBoundsException e) { // expected } } /** * Tests bounds checking for {@link List#remove(int)} on a * full list. */ public void testListRemoveByIndexBoundsChecking2() { if (!isRemoveSupported()) return; List list = makeFullList(); try { list.remove(Integer.MIN_VALUE); fail("List.remove should throw IndexOutOfBoundsException " + "[Integer.MIN_VALUE]"); } catch (IndexOutOfBoundsException e) { // expected } try { list.remove(-1); fail("List.remove should throw IndexOutOfBoundsException [-1]"); } catch (IndexOutOfBoundsException e) { // expected } try { list.remove(getFullElements().length); fail("List.remove should throw IndexOutOfBoundsException [size]"); } catch (IndexOutOfBoundsException e) { // expected } try { list.remove(Integer.MAX_VALUE); fail("List.remove should throw IndexOutOfBoundsException " + "[Integer.MAX_VALUE]"); } catch (IndexOutOfBoundsException e) { // expected } } /** * Tests {@link List#remove(int)}. */ public void testListRemoveByIndex() { if (!isRemoveSupported()) return; int max = getFullElements().length; for (int i = 0; i < max; i++) { resetFull(); Object o1 = ((List) collection).remove(i); Object o2 = ((List) confirmed).remove(i); assertEquals("remove should return correct element", o1, o2); verify(); } } /** * Tests the read-only bits of {@link List#listIterator()}. */ public void testListListIterator() { resetFull(); forwardTest(getList().listIterator(), 0); backwardTest(getList().listIterator(), 0); } /** * Tests the read-only bits of {@link List#listIterator(int)}. */ public void testListListIteratorByIndex() { resetFull(); try { getList().listIterator(-1); } catch (IndexOutOfBoundsException ex) { } resetFull(); try { getList().listIterator(getList().size() + 1); } catch (IndexOutOfBoundsException ex) { } resetFull(); for (int i = 0; i <= confirmed.size(); i++) { forwardTest(getList().listIterator(i), i); backwardTest(getList().listIterator(i), i); } resetFull(); for (int i = 0; i <= confirmed.size(); i++) { backwardTest(getList().listIterator(i), i); } } /** * Tests remove on list iterator is correct. */ public void testListListIteratorPreviousRemove() { if (isRemoveSupported() == false) return; resetFull(); ListIterator it = getList().listIterator(); Object zero = it.next(); Object one = it.next(); Object two = it.next(); Object two2 = it.previous(); Object one2 = it.previous(); assertSame(one, one2); assertSame(two, two2); assertSame(zero, getList().get(0)); assertSame(one, getList().get(1)); assertSame(two, getList().get(2)); it.remove(); assertSame(zero, getList().get(0)); assertSame(two, getList().get(1)); } /** * Traverses to the end of the given iterator. * * @param iter the iterator to traverse * @param i the starting index */ private void forwardTest(ListIterator iter, int i) { List list = getList(); int max = getFullElements().length; while (i < max) { assertTrue("Iterator should have next", iter.hasNext()); assertEquals("Iterator.nextIndex should work", iter.nextIndex(), i); assertEquals("Iterator.previousIndex should work", iter.previousIndex(), i - 1); Object o = iter.next(); assertEquals("Iterator returned correct element", list.get(i), o); i++; } assertTrue("Iterator shouldn't have next", !iter.hasNext()); assertEquals("nextIndex should be size", iter.nextIndex(), max); assertEquals("previousIndex should be size - 1", iter.previousIndex(), max - 1); try { iter.next(); fail("Exhausted iterator should raise NoSuchElement"); } catch (NoSuchElementException e) { // expected } } /** * Traverses to the beginning of the given iterator. * * @param iter the iterator to traverse * @param i the starting index */ private void backwardTest(ListIterator iter, int i) { List list = getList(); while (i > 0) { assertTrue("Iterator should have previous, i:" + i, iter.hasPrevious()); assertEquals("Iterator.nextIndex should work, i:" + i, iter.nextIndex(), i); assertEquals("Iterator.previousIndex should work, i:" + i, iter.previousIndex(), i - 1); Object o = iter.previous(); assertEquals("Iterator returned correct element", list.get(i - 1), o); i--; } assertTrue("Iterator shouldn't have previous", !iter.hasPrevious()); int nextIndex = iter.nextIndex(); assertEquals("nextIndex should be 0, actual value: " + nextIndex, nextIndex, 0); int prevIndex = iter.previousIndex(); assertEquals("previousIndex should be -1, actual value: " + prevIndex, prevIndex, -1); try { iter.previous(); fail("Exhausted iterator should raise NoSuchElement"); } catch (NoSuchElementException e) { // expected } } /** * Tests the {@link ListIterator#add(Object)} method of the list * iterator. */ public void testListIteratorAdd() { if (!isAddSupported()) return; resetEmpty(); List list1 = getList(); List list2 = getConfirmedList(); Object[] elements = getFullElements(); ListIterator iter1 = list1.listIterator(); ListIterator iter2 = list2.listIterator(); for (int i = 0; i < elements.length; i++) { iter1.add(elements[i]); iter2.add(elements[i]); verify(); } resetFull(); iter1 = getList().listIterator(); iter2 = getConfirmedList().listIterator(); for (int i = 0; i < elements.length; i++) { iter1.next(); iter2.next(); iter1.add(elements[i]); iter2.add(elements[i]); verify(); } } /** * Tests the {@link ListIterator#set(Object)} method of the list * iterator. */ public void testListIteratorSet() { if (!isSetSupported()) return; Object[] elements = getFullElements(); resetFull(); ListIterator iter1 = getList().listIterator(); ListIterator iter2 = getConfirmedList().listIterator(); for (int i = 0; i < elements.length; i++) { iter1.next(); iter2.next(); iter1.set(elements[i]); iter2.set(elements[i]); verify(); } } public void testEmptyListSerialization() throws IOException, ClassNotFoundException { List list = makeEmptyList(); if (!(list instanceof Serializable && isTestSerialization())) return; byte[] objekt = writeExternalFormToBytes((Serializable) list); List list2 = (List) readExternalFormFromBytes(objekt); assertTrue("Both lists are empty", list.size() == 0); assertTrue("Both lists are empty", list2.size() == 0); } public void testFullListSerialization() throws IOException, ClassNotFoundException { List list = makeFullList(); int size = getFullElements().length; if (!(list instanceof Serializable && isTestSerialization())) return; byte[] objekt = writeExternalFormToBytes((Serializable) list); List list2 = (List) readExternalFormFromBytes(objekt); assertEquals("Both lists are same size", list.size(), size); assertEquals("Both lists are same size", list2.size(), size); } /** * Compare the current serialized form of the List * against the canonical version in CVS. * GenericsNote: This is not valid with the generics conversion, will reintroduce at a later date */ /* public void testEmptyListCompatibility() throws IOException, ClassNotFoundException { // * Create canonical objects with this code //List list = makeEmptyList(); //if (!(list instanceof Serializable)) return; // //writeExternalFormToDisk((Serializable) list, getCanonicalEmptyCollectionName(list)); // test to make sure the canonical form has been preserved List list = makeEmptyList(); if(list instanceof Serializable && !skipSerializedCanonicalTests() && isTestSerialization()) { List list2 = (List) readExternalFormFromDisk(getCanonicalEmptyCollectionName(list)); assertTrue("List is empty",list2.size() == 0); assertEquals(list, list2); } } */ /** * Compare the current serialized form of the List * against the canonical version in CVS. * GenericsNote: This is not valid with the generics conversion, will reintroduce at a later date */ /* public void testFullListCompatibility() throws IOException, ClassNotFoundException { // * Create canonical objects with this code //List list = makeFullList(); //if (!(list instanceof Serializable)) return; // //writeExternalFormToDisk((Serializable) list, getCanonicalFullCollectionName(list)); // test to make sure the canonical form has been preserved List list = makeFullList(); if(list instanceof Serializable && !skipSerializedCanonicalTests() && isTestSerialization()) { List list2 = (List) readExternalFormFromDisk(getCanonicalFullCollectionName(list)); if (list2.size() == 4) { // old serialized tests return; } assertEquals("List is the right size",list.size(), list2.size()); assertEquals(list, list2); } } */ //----------------------------------------------------------------------- /** * Returns a {@link BulkTest} for testing {@link List#subList(int,int)}. * The returned bulk test will run through every TestList * method, including another bulkTestSubList. * Sublists are tested until the size of the sublist is less than 10. * Each sublist is 6 elements smaller than its parent list. * (By default this means that two rounds of sublists will be tested). * The verify() method is overloaded to test that the original list is * modified when the sublist is. */ public BulkTest bulkTestSubList() { if (getFullElements().length - 6 < 10) return null; return new BulkTestSubList(this); } public static class BulkTestSubList extends AbstractTestList { private AbstractTestList outer; BulkTestSubList(AbstractTestList outer) { super(""); this.outer = outer; } public Object[] getFullElements() { List l = Arrays.asList(outer.getFullElements()); return l.subList(3, l.size() - 3).toArray(); } public Object[] getOtherElements() { return outer.getOtherElements(); } public boolean isAddSupported() { return outer.isAddSupported(); } public boolean isSetSupported() { return outer.isSetSupported(); } public boolean isRemoveSupported() { return outer.isRemoveSupported(); } public List makeEmptyList() { return outer.makeFullList().subList(4, 4); } public List makeFullList() { int size = getFullElements().length; return outer.makeFullList().subList(3, size - 3); } public void resetEmpty() { outer.resetFull(); this.collection = outer.getList().subList(4, 4); this.confirmed = outer.getConfirmedList().subList(4, 4); } public void resetFull() { outer.resetFull(); int size = outer.confirmed.size(); this.collection = outer.getList().subList(3, size - 3); this.confirmed = outer.getConfirmedList().subList(3, size - 3); } public void verify() { super.verify(); outer.verify(); } public boolean isTestSerialization() { return false; } } /** * Tests that a sublist raises a {@link java.util.ConcurrentModificationException ConcurrentModificationException} * if elements are added to the original list. */ public void testListSubListFailFastOnAdd() { if (!isFailFastSupported()) return; if (!isAddSupported()) return; resetFull(); int size = collection.size(); List sub = getList().subList(1, size); getList().add(getOtherElements()[0]); failFastAll(sub); resetFull(); sub = getList().subList(1, size); getList().add(0, getOtherElements()[0]); failFastAll(sub); resetFull(); sub = getList().subList(1, size); getList().addAll(Arrays.asList(getOtherElements())); failFastAll(sub); resetFull(); sub = getList().subList(1, size); getList().addAll(0, Arrays.asList(getOtherElements())); failFastAll(sub); } /** * Tests that a sublist raises a {@link java.util.ConcurrentModificationException ConcurrentModificationException} * if elements are removed from the original list. */ public void testListSubListFailFastOnRemove() { if (!isFailFastSupported()) return; if (!isRemoveSupported()) return; resetFull(); int size = collection.size(); List sub = getList().subList(1, size); getList().remove(0); failFastAll(sub); resetFull(); sub = getList().subList(1, size); getList().remove(getFullElements()[2]); failFastAll(sub); resetFull(); sub = getList().subList(1, size); getList().removeAll(Arrays.asList(getFullElements())); failFastAll(sub); resetFull(); sub = getList().subList(1, size); getList().retainAll(Arrays.asList(getOtherElements())); failFastAll(sub); resetFull(); sub = getList().subList(1, size); getList().clear(); failFastAll(sub); } /** * Invokes all the methods on the given sublist to make sure they raise * a {@link java.util.ConcurrentModificationException ConcurrentModificationException}. */ protected void failFastAll(List list) { Method[] methods = List.class.getMethods(); for (int i = 0; i < methods.length; i++) { failFastMethod(list, methods[i]); } } /** * Invokes the given method on the given sublist to make sure it raises * a {@link java.util.ConcurrentModificationException ConcurrentModificationException}. *

                  * Unless the method happens to be the equals() method, in which case * the test is skipped. There seems to be a bug in * java.util.AbstractList.subList(int,int).equals(Object) -- it never * raises a ConcurrentModificationException. * * @param list the sublist to test * @param m the method to invoke */ protected void failFastMethod(List list, Method m) { if (m.getName().equals("equals")) return; Object element = getOtherElements()[0]; Collection c = Collections.singleton(element); Class[] types = m.getParameterTypes(); Object[] params = new Object[types.length]; for (int i = 0; i < params.length; i++) { if (types[i] == Integer.TYPE) params[i] = new Integer(0); else if (types[i] == Collection.class) params[i] = c; else if (types[i] == Object.class) params[i] = element; else if (types[i] == Object[].class) params[i] = new Object[0]; } try { m.invoke(list, params); fail(m.getName() + " should raise ConcurrentModification"); } catch (IllegalAccessException e) { // impossible } catch (InvocationTargetException e) { Throwable t = e.getTargetException(); if (t instanceof ConcurrentModificationException) { // expected return; } else { fail(m.getName() + " raised unexpected " + e); } } } //----------------------------------------------------------------------- public BulkTest bulkTestListIterator() { return new TestListIterator(); } public class TestListIterator extends AbstractTestListIterator { public TestListIterator() { super("TestListIterator"); } public Object addSetValue() { return AbstractTestList.this.getOtherElements()[0]; } public boolean supportsRemove() { return AbstractTestList.this.isRemoveSupported(); } public boolean supportsAdd() { return AbstractTestList.this.isAddSupported(); } public boolean supportsSet() { return AbstractTestList.this.isSetSupported(); } public ListIterator makeEmptyListIterator() { resetEmpty(); return ((List) AbstractTestList.this.collection).listIterator(); } public ListIterator makeFullListIterator() { resetFull(); return ((List) AbstractTestList.this.collection).listIterator(); } } } collections-generic-4.01/src/test/org/apache/commons/collections15/list/TestAll.java0000644000175000017500000000350310464140763030705 0ustar giovannigiovanni/* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.list; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * Entry point for tests. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 19:11:58 $ * @since Commons Collections 3.0 */ public class TestAll extends TestCase { public TestAll(String testName) { super(testName); } public static void main(String args[]) { String[] testCaseName = {TestAll.class.getName()}; junit.textui.TestRunner.main(testCaseName); } public static Test suite() { TestSuite suite = new TestSuite(); suite.addTest(TestCursorableLinkedList.suite()); suite.addTest(TestNodeCachingLinkedList.suite()); suite.addTest(TestTreeList.suite()); suite.addTest(TestFixedSizeList.suite()); suite.addTest(TestPredicatedList.suite()); suite.addTest(TestSetUniqueList.suite()); suite.addTest(TestSynchronizedList.suite()); suite.addTest(TestTransformedList.suite()); suite.addTest(TestTypedList.suite()); suite.addTest(TestUnmodifiableList.suite()); return suite; } } collections-generic-4.01/src/test/org/apache/commons/collections15/list/TestTransformedList.java0000644000175000017500000001031310464140756033314 0ustar giovannigiovanni/* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.list; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.collections15.collection.TestTransformedCollection; import java.util.*; /** * Extension of {@link TestList} for exercising the {@link TransformedList} * implementation. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 19:11:58 $ * @since Commons Collections 3.0 */ public class TestTransformedList extends AbstractTestList { public TestTransformedList(String testName) { super(testName); } public static Test suite() { return new TestSuite(TestTransformedList.class); } public static void main(String args[]) { String[] testCaseName = {TestTransformedList.class.getName()}; junit.textui.TestRunner.main(testCaseName); } public Collection makeConfirmedCollection() { return new ArrayList(); } public Collection makeConfirmedFullCollection() { List list = new ArrayList(); list.addAll(Arrays.asList(getFullElements())); return list; } public List makeEmptyList() { return TransformedList.decorate(new ArrayList(), TestTransformedCollection.NOOP_TRANSFORMER); } public List makeFullList() { List list = new ArrayList(); list.addAll(Arrays.asList(getFullElements())); return TransformedList.decorate(list, TestTransformedCollection.NOOP_TRANSFORMER); } public void testTransformedList() { List list = TransformedList.decorate(new ArrayList(), TestTransformedCollection.STRING_TO_INTEGER_TRANSFORMER); assertEquals(0, list.size()); Object[] els = new Object[]{"1", "3", "5", "7", "2", "4", "6"}; for (int i = 0; i < els.length; i++) { list.add(els[i]); assertEquals(i + 1, list.size()); assertEquals(true, list.contains(new Integer((String) els[i]))); assertEquals(false, list.contains(els[i])); } assertEquals(false, list.remove(els[0])); assertEquals(true, list.remove(new Integer((String) els[0]))); list.clear(); for (int i = 0; i < els.length; i++) { list.add(0, els[i]); assertEquals(i + 1, list.size()); assertEquals(new Integer((String) els[i]), list.get(0)); } list.set(0, "22"); assertEquals(new Integer(22), list.get(0)); ListIterator it = list.listIterator(); it.next(); it.set("33"); assertEquals(new Integer(33), list.get(0)); it.add("44"); assertEquals(new Integer(44), list.get(1)); List adds = new ArrayList(); adds.add("1"); adds.add("2"); list.clear(); list.addAll(adds); assertEquals(new Integer(1), list.get(0)); assertEquals(new Integer(2), list.get(1)); adds.clear(); adds.add("3"); list.addAll(1, adds); assertEquals(new Integer(1), list.get(0)); assertEquals(new Integer(3), list.get(1)); assertEquals(new Integer(2), list.get(2)); } public String getCompatibilityVersion() { return "3.1"; } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk((java.io.Serializable) collection, "D:/dev/collections15/data/test/TransformedList.emptyCollection.version3.1.obj"); // resetFull(); // writeExternalFormToDisk((java.io.Serializable) collection, "D:/dev/collections15/data/test/TransformedList.fullCollection.version3.1.obj"); // } } collections-generic-4.01/src/test/org/apache/commons/collections15/list/TestUnmodifiableList.java0000644000175000017500000001272610464140760033433 0ustar giovannigiovanni/* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.list; import junit.framework.Test; import junit.framework.TestSuite; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; /** * Extension of {@link AbstractTestList} for exercising the * {@link UnmodifiableList} implementation. * * @author Matt Hall, John Watkinson, Phil Steitz * @version $Revision: 1.1 $ $Date: 2005/10/11 19:11:58 $ * @since Commons Collections 3.0 */ public class TestUnmodifiableList extends AbstractTestList { public TestUnmodifiableList(String testName) { super(testName); } public static Test suite() { return new TestSuite(TestUnmodifiableList.class); } public static void main(String args[]) { String[] testCaseName = {TestUnmodifiableList.class.getName()}; junit.textui.TestRunner.main(testCaseName); } //----------------------------------------------------------------------- public List makeEmptyList() { return UnmodifiableList.decorate(new ArrayList()); } public List makeFullList() { ArrayList list = new ArrayList(); list.addAll(Arrays.asList(getFullElements())); return UnmodifiableList.decorate(list); } public boolean isSetSupported() { return false; } public boolean isAddSupported() { return false; } public boolean isRemoveSupported() { return false; } //----------------------------------------------------------------------- protected UnmodifiableList list = null; protected ArrayList array = null; protected void setupList() { list = (UnmodifiableList) makeFullList(); array = new ArrayList(); array.add(new Integer(1)); } /** * Verify that base list and sublists are not modifiable */ public void testUnmodifiable() { setupList(); verifyUnmodifiable(list); verifyUnmodifiable(list.subList(0, 2)); } protected void verifyUnmodifiable(List list) { try { list.add(0, new Integer(0)); fail("Expecting UnsupportedOperationException."); } catch (UnsupportedOperationException e) { // expected } try { list.add(new Integer(0)); fail("Expecting UnsupportedOperationException."); } catch (UnsupportedOperationException e) { // expected } try { list.addAll(0, array); fail("Expecting UnsupportedOperationException."); } catch (UnsupportedOperationException e) { // expected } try { list.addAll(array); fail("Expecting UnsupportedOperationException."); } catch (UnsupportedOperationException e) { // expected } try { list.clear(); fail("Expecting UnsupportedOperationException."); } catch (UnsupportedOperationException e) { // expected } try { list.remove(0); fail("Expecting UnsupportedOperationException."); } catch (UnsupportedOperationException e) { // expected } try { list.remove(new Integer(0)); fail("Expecting UnsupportedOperationException."); } catch (UnsupportedOperationException e) { // expected } try { list.removeAll(array); fail("Expecting UnsupportedOperationException."); } catch (UnsupportedOperationException e) { // expected } try { list.retainAll(array); fail("Expecting UnsupportedOperationException."); } catch (UnsupportedOperationException e) { // expected } try { list.set(0, new Integer(0)); fail("Expecting UnsupportedOperationException."); } catch (UnsupportedOperationException e) { // expected } } /** * Verify that iterator is not modifiable */ public void testUnmodifiableIterator() { setupList(); Iterator iterator = list.iterator(); try { Object obj = iterator.next(); iterator.remove(); fail("Expecting UnsupportedOperationException."); } catch (UnsupportedOperationException e) { // expected } } public String getCompatibilityVersion() { return "3.1"; } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk((java.io.Serializable) collection, "D:/dev/collections15/data/test/UnmodifiableList.emptyCollection.version3.1.obj"); // resetFull(); // writeExternalFormToDisk((java.io.Serializable) collection, "D:/dev/collections15/data/test/UnmodifiableList.fullCollection.version3.1.obj"); // } } collections-generic-4.01/src/test/org/apache/commons/collections15/TestIteratorUtils.java0000644000175000017500000006406710464140764032051 0ustar giovannigiovanni/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15; import junit.framework.Test; import org.apache.commons.collections15.iterators.*; import java.util.*; /** * Tests for IteratorUtils. * * @author Matt Hall, John Watkinson, Unknown * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:39 $ */ public class TestIteratorUtils extends BulkTest { public TestIteratorUtils(String name) { super(name); } public static void main(String args[]) { junit.textui.TestRunner.run(suite()); } public static Test suite() { return BulkTest.makeSuite(TestIteratorUtils.class); } public void testToList() { List list = new ArrayList(); list.add(new Integer(1)); list.add("Two"); list.add(null); List result = IteratorUtils.toList(list.iterator()); assertEquals(list, result); } public void testToArray() { List list = new ArrayList(); list.add(new Integer(1)); list.add("Two"); list.add(null); Object[] result = IteratorUtils.toArray(list.iterator()); assertEquals(list, Arrays.asList(result)); } public void testToArray2() { List list = new ArrayList(); list.add("One"); list.add("Two"); list.add(null); String[] result = (String[]) IteratorUtils.toArray(list.iterator(), String.class); assertEquals(list, Arrays.asList(result)); } public void testArrayIterator() { Object[] objArray = {"a", "b", "c"}; ResettableIterator iterator = IteratorUtils.arrayIterator(objArray); assertTrue(iterator.next().equals("a")); assertTrue(iterator.next().equals("b")); iterator.reset(); assertTrue(iterator.next().equals("a")); try { iterator = IteratorUtils.arrayIterator(new Integer(0)); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) { // expected } try { iterator = IteratorUtils.arrayIterator(null); fail("Expecting NullPointerException"); } catch (NullPointerException ex) { // expected } iterator = IteratorUtils.arrayIterator(objArray, 1); assertTrue(iterator.next().equals("b")); try { iterator = IteratorUtils.arrayIterator(objArray, -1); fail("Expecting IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException ex) { // expected } iterator = IteratorUtils.arrayIterator(objArray, 3); assertTrue(!iterator.hasNext()); iterator.reset(); try { iterator = IteratorUtils.arrayIterator(objArray, 4); fail("Expecting IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException ex) { // expected } iterator = IteratorUtils.arrayIterator(objArray, 2, 3); assertTrue(iterator.next().equals("c")); try { iterator = IteratorUtils.arrayIterator(objArray, 2, 4); fail("Expecting IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException ex) { // expected } try { iterator = IteratorUtils.arrayIterator(objArray, -1, 1); fail("Expecting IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException ex) { // expected } try { iterator = IteratorUtils.arrayIterator(objArray, 2, 1); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) { // expected } int[] intArray = {0, 1, 2}; iterator = IteratorUtils.arrayIterator(intArray); assertTrue(iterator.next().equals(new Integer(0))); assertTrue(iterator.next().equals(new Integer(1))); iterator.reset(); assertTrue(iterator.next().equals(new Integer(0))); iterator = IteratorUtils.arrayIterator(intArray, 1); assertTrue(iterator.next().equals(new Integer(1))); try { iterator = IteratorUtils.arrayIterator(intArray, -1); fail("Expecting IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException ex) { // expected } iterator = IteratorUtils.arrayIterator(intArray, 3); assertTrue(!iterator.hasNext()); iterator.reset(); try { iterator = IteratorUtils.arrayIterator(intArray, 4); fail("Expecting IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException ex) { // expected } iterator = IteratorUtils.arrayIterator(intArray, 2, 3); assertTrue(iterator.next().equals(new Integer(2))); try { iterator = IteratorUtils.arrayIterator(intArray, 2, 4); fail("Expecting IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException ex) { // expected } try { iterator = IteratorUtils.arrayIterator(intArray, -1, 1); fail("Expecting IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException ex) { // expected } try { iterator = IteratorUtils.arrayIterator(intArray, 2, 1); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) { // expected } } public void testArrayListIterator() { Object[] objArray = {"a", "b", "c", "d"}; ResettableListIterator iterator = IteratorUtils.arrayListIterator(objArray); assertTrue(!iterator.hasPrevious()); assertTrue(iterator.previousIndex() == -1); assertTrue(iterator.nextIndex() == 0); assertTrue(iterator.next().equals("a")); assertTrue(iterator.previous().equals("a")); assertTrue(iterator.next().equals("a")); assertTrue(iterator.previousIndex() == 0); assertTrue(iterator.nextIndex() == 1); assertTrue(iterator.next().equals("b")); assertTrue(iterator.next().equals("c")); assertTrue(iterator.next().equals("d")); assertTrue(iterator.nextIndex() == 4); // size of list assertTrue(iterator.previousIndex() == 3); try { iterator = IteratorUtils.arrayListIterator(new Integer(0)); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) { // expected } try { iterator = IteratorUtils.arrayListIterator(null); fail("Expecting NullPointerException"); } catch (NullPointerException ex) { // expected } iterator = IteratorUtils.arrayListIterator(objArray, 1); assertTrue(iterator.previousIndex() == -1); assertTrue(!iterator.hasPrevious()); assertTrue(iterator.nextIndex() == 0); assertTrue(iterator.next().equals("b")); assertTrue(iterator.previousIndex() == 0); try { iterator = IteratorUtils.arrayListIterator(objArray, -1); fail("Expecting IndexOutOfBoundsException."); } catch (IndexOutOfBoundsException ex) { // expected } iterator = IteratorUtils.arrayListIterator(objArray, 3); assertTrue(iterator.hasNext()); try { Object x = iterator.previous(); fail("Expecting NoSuchElementException."); } catch (NoSuchElementException ex) { // expected } try { iterator = IteratorUtils.arrayListIterator(objArray, 5); fail("Expecting IndexOutOfBoundsException."); } catch (IndexOutOfBoundsException ex) { // expected } iterator = IteratorUtils.arrayListIterator(objArray, 2, 3); assertTrue(iterator.next().equals("c")); try { iterator = IteratorUtils.arrayListIterator(objArray, 2, 5); fail("Expecting IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException ex) { // expected } try { iterator = IteratorUtils.arrayListIterator(objArray, -1, 1); fail("Expecting IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException ex) { // expected } try { iterator = IteratorUtils.arrayListIterator(objArray, 2, 1); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) { // expected } int[] intArray = {0, 1, 2}; iterator = IteratorUtils.arrayListIterator(intArray); assertTrue(iterator.previousIndex() == -1); assertTrue(!iterator.hasPrevious()); assertTrue(iterator.nextIndex() == 0); assertTrue(iterator.next().equals(new Integer(0))); assertTrue(iterator.previousIndex() == 0); assertTrue(iterator.nextIndex() == 1); assertTrue(iterator.next().equals(new Integer(1))); assertTrue(iterator.previousIndex() == 1); assertTrue(iterator.nextIndex() == 2); assertTrue(iterator.previous().equals(new Integer(1))); assertTrue(iterator.next().equals(new Integer(1))); iterator = IteratorUtils.arrayListIterator(intArray, 1); assertTrue(iterator.previousIndex() == -1); assertTrue(!iterator.hasPrevious()); assertTrue(iterator.nextIndex() == 0); assertTrue(iterator.next().equals(new Integer(1))); assertTrue(iterator.previous().equals(new Integer(1))); assertTrue(iterator.next().equals(new Integer(1))); assertTrue(iterator.previousIndex() == 0); assertTrue(iterator.nextIndex() == 1); assertTrue(iterator.next().equals(new Integer(2))); assertTrue(iterator.previousIndex() == 1); assertTrue(iterator.nextIndex() == 2); assertTrue(iterator.previous().equals(new Integer(2))); assertTrue(iterator.previousIndex() == 0); assertTrue(iterator.nextIndex() == 1); try { iterator = IteratorUtils.arrayListIterator(intArray, -1); fail("Expecting IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException ex) { // expected } iterator = IteratorUtils.arrayListIterator(intArray, 3); assertTrue(!iterator.hasNext()); try { iterator = IteratorUtils.arrayListIterator(intArray, 4); fail("Expecting IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException ex) { // expected } iterator = IteratorUtils.arrayListIterator(intArray, 2, 3); assertTrue(!iterator.hasPrevious()); assertTrue(iterator.previousIndex() == -1); assertTrue(iterator.next().equals(new Integer(2))); assertTrue(iterator.hasPrevious()); assertTrue(!iterator.hasNext()); try { iterator = IteratorUtils.arrayListIterator(intArray, 2, 4); fail("Expecting IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException ex) { // expected } try { iterator = IteratorUtils.arrayListIterator(intArray, -1, 1); fail("Expecting IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException ex) { // expected } try { iterator = IteratorUtils.arrayListIterator(intArray, 2, 1); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) { // expected } } /** * Gets an immutable Iterator operating on the elements ["a", "b", "c", "d"]. */ private Iterator getImmutableIterator() { List list = new ArrayList(); list.add("a"); list.add("b"); list.add("c"); list.add("d"); return IteratorUtils.unmodifiableIterator(list.iterator()); } /** * Gets an immutable ListIterator operating on the elements ["a", "b", "c", "d"]. */ private ListIterator getImmutableListIterator() { List list = new ArrayList(); list.add("a"); list.add("b"); list.add("c"); list.add("d"); return IteratorUtils.unmodifiableListIterator(list.listIterator()); } //----------------------------------------------------------------------- /** * Test empty iterator */ public void testEmptyIterator() { assertSame(EmptyIterator.INSTANCE, IteratorUtils.EMPTY_ITERATOR); assertSame(EmptyIterator.RESETTABLE_INSTANCE, IteratorUtils.EMPTY_ITERATOR); assertEquals(true, IteratorUtils.EMPTY_ITERATOR instanceof Iterator); assertEquals(true, IteratorUtils.EMPTY_ITERATOR instanceof ResettableIterator); assertEquals(false, IteratorUtils.EMPTY_ITERATOR instanceof OrderedIterator); assertEquals(false, IteratorUtils.EMPTY_ITERATOR instanceof ListIterator); assertEquals(false, IteratorUtils.EMPTY_ITERATOR instanceof MapIterator); assertEquals(false, IteratorUtils.EMPTY_ITERATOR.hasNext()); IteratorUtils.EMPTY_ITERATOR.reset(); assertSame(IteratorUtils.EMPTY_ITERATOR, IteratorUtils.EMPTY_ITERATOR); assertSame(IteratorUtils.EMPTY_ITERATOR, IteratorUtils.emptyIterator()); try { IteratorUtils.EMPTY_ITERATOR.next(); fail(); } catch (NoSuchElementException ex) { } try { IteratorUtils.EMPTY_ITERATOR.remove(); fail(); } catch (IllegalStateException ex) { } } //----------------------------------------------------------------------- /** * Test empty list iterator */ public void testEmptyListIterator() { assertSame(EmptyListIterator.INSTANCE, IteratorUtils.EMPTY_LIST_ITERATOR); assertSame(EmptyListIterator.RESETTABLE_INSTANCE, IteratorUtils.EMPTY_LIST_ITERATOR); assertEquals(true, IteratorUtils.EMPTY_LIST_ITERATOR instanceof Iterator); assertEquals(true, IteratorUtils.EMPTY_LIST_ITERATOR instanceof ListIterator); assertEquals(true, IteratorUtils.EMPTY_LIST_ITERATOR instanceof ResettableIterator); assertEquals(true, IteratorUtils.EMPTY_LIST_ITERATOR instanceof ResettableListIterator); assertEquals(false, IteratorUtils.EMPTY_LIST_ITERATOR instanceof MapIterator); assertEquals(false, IteratorUtils.EMPTY_LIST_ITERATOR.hasNext()); assertEquals(0, IteratorUtils.EMPTY_LIST_ITERATOR.nextIndex()); assertEquals(-1, IteratorUtils.EMPTY_LIST_ITERATOR.previousIndex()); IteratorUtils.EMPTY_LIST_ITERATOR.reset(); assertSame(IteratorUtils.EMPTY_LIST_ITERATOR, IteratorUtils.EMPTY_LIST_ITERATOR); assertSame(IteratorUtils.EMPTY_LIST_ITERATOR, IteratorUtils.emptyListIterator()); try { IteratorUtils.EMPTY_LIST_ITERATOR.next(); fail(); } catch (NoSuchElementException ex) { } try { IteratorUtils.EMPTY_LIST_ITERATOR.previous(); fail(); } catch (NoSuchElementException ex) { } try { IteratorUtils.EMPTY_LIST_ITERATOR.remove(); fail(); } catch (IllegalStateException ex) { } try { IteratorUtils.EMPTY_LIST_ITERATOR.set(null); fail(); } catch (IllegalStateException ex) { } try { IteratorUtils.EMPTY_LIST_ITERATOR.add(null); fail(); } catch (UnsupportedOperationException ex) { } } //----------------------------------------------------------------------- /** * Test empty map iterator */ public void testEmptyMapIterator() { assertSame(EmptyMapIterator.INSTANCE, IteratorUtils.EMPTY_MAP_ITERATOR); assertEquals(true, IteratorUtils.EMPTY_MAP_ITERATOR instanceof Iterator); assertEquals(true, IteratorUtils.EMPTY_MAP_ITERATOR instanceof MapIterator); assertEquals(true, IteratorUtils.EMPTY_MAP_ITERATOR instanceof ResettableIterator); assertEquals(false, IteratorUtils.EMPTY_MAP_ITERATOR instanceof ListIterator); assertEquals(false, IteratorUtils.EMPTY_MAP_ITERATOR instanceof OrderedIterator); assertEquals(false, IteratorUtils.EMPTY_MAP_ITERATOR instanceof OrderedMapIterator); assertEquals(false, IteratorUtils.EMPTY_MAP_ITERATOR.hasNext()); ((ResettableIterator) IteratorUtils.EMPTY_MAP_ITERATOR).reset(); assertSame(IteratorUtils.EMPTY_MAP_ITERATOR, IteratorUtils.EMPTY_MAP_ITERATOR); assertSame(IteratorUtils.EMPTY_MAP_ITERATOR, IteratorUtils.emptyMapIterator()); try { IteratorUtils.EMPTY_MAP_ITERATOR.next(); fail(); } catch (NoSuchElementException ex) { } try { IteratorUtils.EMPTY_MAP_ITERATOR.remove(); fail(); } catch (IllegalStateException ex) { } try { IteratorUtils.EMPTY_MAP_ITERATOR.getKey(); fail(); } catch (IllegalStateException ex) { } try { IteratorUtils.EMPTY_MAP_ITERATOR.getValue(); fail(); } catch (IllegalStateException ex) { } try { IteratorUtils.EMPTY_MAP_ITERATOR.setValue(null); fail(); } catch (IllegalStateException ex) { } } //----------------------------------------------------------------------- /** * Test empty map iterator */ public void testEmptyOrderedIterator() { assertSame(EmptyOrderedIterator.INSTANCE, IteratorUtils.EMPTY_ORDERED_ITERATOR); assertEquals(true, IteratorUtils.EMPTY_ORDERED_ITERATOR instanceof Iterator); assertEquals(true, IteratorUtils.EMPTY_ORDERED_ITERATOR instanceof OrderedIterator); assertEquals(true, IteratorUtils.EMPTY_ORDERED_ITERATOR instanceof ResettableIterator); assertEquals(false, IteratorUtils.EMPTY_ORDERED_ITERATOR instanceof ListIterator); assertEquals(false, IteratorUtils.EMPTY_ORDERED_ITERATOR instanceof MapIterator); assertEquals(false, IteratorUtils.EMPTY_ORDERED_ITERATOR.hasNext()); assertEquals(false, IteratorUtils.EMPTY_ORDERED_ITERATOR.hasPrevious()); ((ResettableIterator) IteratorUtils.EMPTY_ORDERED_ITERATOR).reset(); assertSame(IteratorUtils.EMPTY_ORDERED_ITERATOR, IteratorUtils.EMPTY_ORDERED_ITERATOR); assertSame(IteratorUtils.EMPTY_ORDERED_ITERATOR, IteratorUtils.emptyOrderedIterator()); try { IteratorUtils.EMPTY_ORDERED_ITERATOR.next(); fail(); } catch (NoSuchElementException ex) { } try { IteratorUtils.EMPTY_ORDERED_ITERATOR.previous(); fail(); } catch (NoSuchElementException ex) { } try { IteratorUtils.EMPTY_ORDERED_ITERATOR.remove(); fail(); } catch (IllegalStateException ex) { } } //----------------------------------------------------------------------- /** * Test empty map iterator */ public void testEmptyOrderedMapIterator() { assertSame(EmptyOrderedMapIterator.INSTANCE, IteratorUtils.EMPTY_ORDERED_MAP_ITERATOR); assertEquals(true, IteratorUtils.EMPTY_ORDERED_MAP_ITERATOR instanceof Iterator); assertEquals(true, IteratorUtils.EMPTY_ORDERED_MAP_ITERATOR instanceof MapIterator); assertEquals(true, IteratorUtils.EMPTY_ORDERED_MAP_ITERATOR instanceof OrderedMapIterator); assertEquals(true, IteratorUtils.EMPTY_ORDERED_MAP_ITERATOR instanceof ResettableIterator); assertEquals(false, IteratorUtils.EMPTY_ORDERED_MAP_ITERATOR instanceof ListIterator); assertEquals(false, IteratorUtils.EMPTY_ORDERED_MAP_ITERATOR.hasNext()); assertEquals(false, IteratorUtils.EMPTY_ORDERED_MAP_ITERATOR.hasPrevious()); ((ResettableIterator) IteratorUtils.EMPTY_ORDERED_MAP_ITERATOR).reset(); assertSame(IteratorUtils.EMPTY_ORDERED_MAP_ITERATOR, IteratorUtils.EMPTY_ORDERED_MAP_ITERATOR); assertSame(IteratorUtils.EMPTY_ORDERED_MAP_ITERATOR, IteratorUtils.emptyOrderedMapIterator()); try { IteratorUtils.EMPTY_ORDERED_MAP_ITERATOR.next(); fail(); } catch (NoSuchElementException ex) { } try { IteratorUtils.EMPTY_ORDERED_MAP_ITERATOR.previous(); fail(); } catch (NoSuchElementException ex) { } try { IteratorUtils.EMPTY_ORDERED_MAP_ITERATOR.remove(); fail(); } catch (IllegalStateException ex) { } try { IteratorUtils.EMPTY_ORDERED_MAP_ITERATOR.getKey(); fail(); } catch (IllegalStateException ex) { } try { IteratorUtils.EMPTY_ORDERED_MAP_ITERATOR.getValue(); fail(); } catch (IllegalStateException ex) { } try { IteratorUtils.EMPTY_ORDERED_MAP_ITERATOR.setValue(null); fail(); } catch (IllegalStateException ex) { } } //----------------------------------------------------------------------- /** * Test next() and hasNext() for an immutable Iterator. */ public void testUnmodifiableIteratorIteration() { Iterator iterator = getImmutableIterator(); assertTrue(iterator.hasNext()); assertEquals("a", iterator.next()); assertTrue(iterator.hasNext()); assertEquals("b", iterator.next()); assertTrue(iterator.hasNext()); assertEquals("c", iterator.next()); assertTrue(iterator.hasNext()); assertEquals("d", iterator.next()); assertTrue(!iterator.hasNext()); } /** * Test next(), hasNext(), previous() and hasPrevious() for an immutable * ListIterator. */ public void testUnmodifiableListIteratorIteration() { ListIterator listIterator = getImmutableListIterator(); assertTrue(!listIterator.hasPrevious()); assertTrue(listIterator.hasNext()); assertEquals("a", listIterator.next()); assertTrue(listIterator.hasPrevious()); assertTrue(listIterator.hasNext()); assertEquals("b", listIterator.next()); assertTrue(listIterator.hasPrevious()); assertTrue(listIterator.hasNext()); assertEquals("c", listIterator.next()); assertTrue(listIterator.hasPrevious()); assertTrue(listIterator.hasNext()); assertEquals("d", listIterator.next()); assertTrue(listIterator.hasPrevious()); assertTrue(!listIterator.hasNext()); assertEquals("d", listIterator.previous()); assertTrue(listIterator.hasPrevious()); assertTrue(listIterator.hasNext()); assertEquals("c", listIterator.previous()); assertTrue(listIterator.hasPrevious()); assertTrue(listIterator.hasNext()); assertEquals("b", listIterator.previous()); assertTrue(listIterator.hasPrevious()); assertTrue(listIterator.hasNext()); assertEquals("a", listIterator.previous()); assertTrue(!listIterator.hasPrevious()); assertTrue(listIterator.hasNext()); } /** * Test remove() for an immutable Iterator. */ public void testUnmodifiableIteratorImmutability() { Iterator iterator = getImmutableIterator(); try { iterator.remove(); // We shouldn't get to here. fail("remove() should throw an UnsupportedOperationException"); } catch (UnsupportedOperationException e) { // This is correct; ignore the exception. } iterator.next(); try { iterator.remove(); // We shouldn't get to here. fail("remove() should throw an UnsupportedOperationException"); } catch (UnsupportedOperationException e) { // This is correct; ignore the exception. } } /** * Test remove() for an immutable ListIterator. */ public void testUnmodifiableListIteratorImmutability() { ListIterator listIterator = getImmutableListIterator(); try { listIterator.remove(); // We shouldn't get to here. fail("remove() should throw an UnsupportedOperationException"); } catch (UnsupportedOperationException e) { // This is correct; ignore the exception. } try { listIterator.set("a"); // We shouldn't get to here. fail("set(Object) should throw an UnsupportedOperationException"); } catch (UnsupportedOperationException e) { // This is correct; ignore the exception. } try { listIterator.add("a"); // We shouldn't get to here. fail("add(Object) should throw an UnsupportedOperationException"); } catch (UnsupportedOperationException e) { // This is correct; ignore the exception. } listIterator.next(); try { listIterator.remove(); // We shouldn't get to here. fail("remove() should throw an UnsupportedOperationException"); } catch (UnsupportedOperationException e) { // This is correct; ignore the exception. } try { listIterator.set("a"); // We shouldn't get to here. fail("set(Object) should throw an UnsupportedOperationException"); } catch (UnsupportedOperationException e) { // This is correct; ignore the exception. } try { listIterator.add("a"); // We shouldn't get to here. fail("add(Object) should throw an UnsupportedOperationException"); } catch (UnsupportedOperationException e) { // This is correct; ignore the exception. } } } collections-generic-4.01/src/test/org/apache/commons/collections15/bag/0000755000175000017500000000000011664401370026244 5ustar giovannigiovannicollections-generic-4.01/src/test/org/apache/commons/collections15/bag/TestHashBag.java0000644000175000017500000000377410464140763031262 0ustar giovannigiovanni/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.bag; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.collections15.Bag; /** * Extension of {@link TestBag} for exercising the {@link HashBag} * implementation. * * @author Matt Hall, John Watkinson, Chuck Burdick * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:44 $ */ public class TestHashBag extends AbstractTestBag { public TestHashBag(String testName) { super(testName); } public static Test suite() { return new TestSuite(TestHashBag.class); } public static void main(String args[]) { String[] testCaseName = {TestHashBag.class.getName()}; junit.textui.TestRunner.main(testCaseName); } public Bag makeBag() { return new HashBag(); } public String getCompatibilityVersion() { return "3"; } // public void testCreate() throws Exception { // Bag bag = makeBag(); // writeExternalFormToDisk((Serializable) bag, "D:/dev/collections15/data/test/HashBag.emptyCollection.version3.obj"); // bag = makeBag(); // bag.add("A"); // bag.add("A"); // bag.add("B"); // bag.add("B"); // bag.add("C"); // writeExternalFormToDisk((Serializable) bag, "D:/dev/collections15/data/test/HashBag.fullCollection.version3.obj"); // } } collections-generic-4.01/src/test/org/apache/commons/collections15/bag/TestPredicatedSortedBag.java0000644000175000017500000001022110464140763033605 0ustar giovannigiovanni/* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.bag; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.collections15.Bag; import org.apache.commons.collections15.Predicate; import org.apache.commons.collections15.PredicateUtils; import org.apache.commons.collections15.SortedBag; import java.util.Comparator; /** * Extension of {@link TestBag} for exercising the {@link PredicatedSortedBag} * implementation. * * @author Matt Hall, John Watkinson, Phil Steitz * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:44 $ * @since Commons Collections 3.0 */ public class TestPredicatedSortedBag extends AbstractTestSortedBag { private SortedBag nullBag = null; public TestPredicatedSortedBag(String testName) { super(testName); } public static Test suite() { return new TestSuite(TestPredicatedSortedBag.class); } public static void main(String args[]) { String[] testCaseName = {TestPredicatedSortedBag.class.getName()}; junit.textui.TestRunner.main(testCaseName); } //-------------------------------------------------------------------------- protected Predicate stringPredicate() { return new Predicate() { public boolean evaluate(Object o) { return o instanceof String; } }; } protected Predicate truePredicate = PredicateUtils.truePredicate(); protected SortedBag decorateBag(SortedBag bag, Predicate predicate) { return PredicatedSortedBag.decorate(bag, predicate); } public Bag makeBag() { return decorateBag(new TreeBag(), truePredicate); } protected Bag makeTestBag() { return decorateBag(new TreeBag(), stringPredicate()); } //-------------------------------------------------------------------------- public void testDecorate() { SortedBag bag = decorateBag(new TreeBag(), stringPredicate()); SortedBag bag2 = ((PredicatedSortedBag) bag).getSortedBag(); try { SortedBag bag3 = decorateBag(new TreeBag(), null); fail("Expecting IllegalArgumentException for null predicate"); } catch (IllegalArgumentException e) { } try { SortedBag bag4 = decorateBag(nullBag, stringPredicate()); fail("Expecting IllegalArgumentException for null bag"); } catch (IllegalArgumentException e) { } } public void testSortOrder() { SortedBag bag = decorateBag(new TreeBag(), stringPredicate()); String one = "one"; String two = "two"; String three = "three"; bag.add(one); bag.add(two); bag.add(three); assertEquals("first element", bag.first(), one); assertEquals("last element", bag.last(), two); Comparator c = bag.comparator(); assertTrue("natural order, so comparator should be null", c == null); } public String getCompatibilityVersion() { return "3.1"; } // public void testCreate() throws Exception { // Bag bag = makeBag(); // writeExternalFormToDisk((java.io.Serializable) bag, "D:/dev/collections15/data/test/PredicatedSortedBag.emptyCollection.version3.1.obj"); // bag = makeBag(); // bag.add("A"); // bag.add("A"); // bag.add("B"); // bag.add("B"); // bag.add("C"); // writeExternalFormToDisk((java.io.Serializable) bag, "D:/dev/collections15/data/test/PredicatedSortedBag.fullCollection.version3.1.obj"); // } } collections-generic-4.01/src/test/org/apache/commons/collections15/bag/TestTypedSortedBag.java0000644000175000017500000000635110464140755032640 0ustar giovannigiovanni/* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.bag; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.collections15.Bag; import org.apache.commons.collections15.SortedBag; import java.util.Comparator; /** * Extension of {@link TestBag} for exercising the {@link TypedSortedBag} * implementation. * * @author Matt Hall, John Watkinson, Phil Steitz * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:44 $ * @since Commons Collections 3.0 */ public class TestTypedSortedBag extends AbstractTestSortedBag { public TestTypedSortedBag(String testName) { super(testName); } public static Test suite() { return new TestSuite(TestTypedSortedBag.class); } public static void main(String args[]) { String[] testCaseName = {TestTypedSortedBag.class.getName()}; junit.textui.TestRunner.main(testCaseName); } //-------------------------------------------------------------------------- protected Class stringClass = this.getName().getClass(); private Object obj = new Object(); protected Class objectClass = obj.getClass(); protected SortedBag nullBag = null; protected SortedBag decorateBag(SortedBag bag, Class claz) { return TypedSortedBag.decorate(bag, claz); } public Bag makeBag() { return decorateBag(new TreeBag(), objectClass); } protected Bag makeTestBag() { return decorateBag(new TreeBag(), stringClass); } //-------------------------------------------------------------------------- public void testDecorate() { SortedBag bag = decorateBag(new TreeBag(), stringClass); try { SortedBag bag3 = decorateBag(new TreeBag(), null); fail("Expecting IllegalArgumentException for null predicate"); } catch (IllegalArgumentException e) { } try { SortedBag bag4 = decorateBag(nullBag, stringClass); fail("Expecting IllegalArgumentException for null bag"); } catch (IllegalArgumentException e) { } } public void testSortOrder() { SortedBag bag = decorateBag(new TreeBag(), stringClass); String one = "one"; String two = "two"; String three = "three"; bag.add(one); bag.add(two); bag.add(three); assertEquals("first element", bag.first(), one); assertEquals("last element", bag.last(), two); Comparator c = bag.comparator(); assertTrue("natural order, so comparator should be null", c == null); } protected boolean skipSerializedCanonicalTests() { return true; } } collections-generic-4.01/src/test/org/apache/commons/collections15/bag/TestTransformedSortedBag.java0000644000175000017500000000554510464140756034044 0ustar giovannigiovanni/* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.bag; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.collections15.Bag; import org.apache.commons.collections15.collection.TestTransformedCollection; /** * Extension of {@link TestSortedBag} for exercising the {@link TransformedSortedBag} * implementation. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:44 $ * @since Commons Collections 3.0 */ public class TestTransformedSortedBag extends AbstractTestSortedBag { public TestTransformedSortedBag(String testName) { super(testName); } public static Test suite() { return new TestSuite(TestTransformedSortedBag.class); } public static void main(String args[]) { String[] testCaseName = {TestTransformedSortedBag.class.getName()}; junit.textui.TestRunner.main(testCaseName); } public Bag makeBag() { return TransformedSortedBag.decorate(new TreeBag(), TestTransformedCollection.NOOP_TRANSFORMER); } public void testTransformedBag() { Bag bag = TransformedSortedBag.decorate(new TreeBag(), TestTransformedCollection.STRING_TO_INTEGER_TRANSFORMER); assertEquals(0, bag.size()); Object[] els = new Object[]{"1", "3", "5", "7", "2", "4", "6"}; for (int i = 0; i < els.length; i++) { bag.add(els[i]); assertEquals(i + 1, bag.size()); assertEquals(true, bag.contains(new Integer((String) els[i]))); } assertEquals(true, bag.remove(new Integer((String) els[0]))); } public String getCompatibilityVersion() { return "3.1"; } // public void testCreate() throws Exception { // Bag bag = makeBag(); // writeExternalFormToDisk((java.io.Serializable) bag, "D:/dev/collections15/data/test/TransformedSortedBag.emptyCollection.version3.1.obj"); // bag = makeBag(); // bag.add("A"); // bag.add("A"); // bag.add("B"); // bag.add("B"); // bag.add("C"); // writeExternalFormToDisk((java.io.Serializable) bag, "D:/dev/collections15/data/test/TransformedSortedBag.fullCollection.version3.1.obj"); // } } collections-generic-4.01/src/test/org/apache/commons/collections15/bag/TestTransformedBag.java0000644000175000017500000000561310464140757032660 0ustar giovannigiovanni/* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.bag; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.collections15.Bag; import org.apache.commons.collections15.collection.TestTransformedCollection; /** * Extension of {@link TestBag} for exercising the {@link TransformedBag} * implementation. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:44 $ * @since Commons Collections 3.0 */ public class TestTransformedBag extends AbstractTestBag { public TestTransformedBag(String testName) { super(testName); } public static Test suite() { return new TestSuite(TestTransformedBag.class); } public static void main(String args[]) { String[] testCaseName = {TestTransformedBag.class.getName()}; junit.textui.TestRunner.main(testCaseName); } public Bag makeBag() { return TransformedBag.decorate(new HashBag(), TestTransformedCollection.NOOP_TRANSFORMER); } public void testTransformedBag() { Bag bag = TransformedBag.decorate(new HashBag(), TestTransformedCollection.STRING_TO_INTEGER_TRANSFORMER); assertEquals(0, bag.size()); Object[] els = new Object[]{"1", "3", "5", "7", "2", "4", "6"}; for (int i = 0; i < els.length; i++) { bag.add(els[i]); assertEquals(i + 1, bag.size()); assertEquals(true, bag.contains(new Integer((String) els[i]))); assertEquals(false, bag.contains(els[i])); } assertEquals(false, bag.remove(els[0])); assertEquals(true, bag.remove(new Integer((String) els[0]))); } public String getCompatibilityVersion() { return "3.1"; } // public void testCreate() throws Exception { // Bag bag = makeBag(); // writeExternalFormToDisk((java.io.Serializable) bag, "D:/dev/collections15/data/test/TransformedBag.emptyCollection.version3.1.obj"); // bag = makeBag(); // bag.add("A"); // bag.add("A"); // bag.add("B"); // bag.add("B"); // bag.add("C"); // writeExternalFormToDisk((java.io.Serializable) bag, "D:/dev/collections15/data/test/TransformedBag.fullCollection.version3.1.obj"); // } } collections-generic-4.01/src/test/org/apache/commons/collections15/bag/TestPredicatedBag.java0000644000175000017500000001117410464140757032437 0ustar giovannigiovanni/* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.bag; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.collections15.Bag; import org.apache.commons.collections15.Predicate; import org.apache.commons.collections15.PredicateUtils; import java.util.Set; /** * Extension of {@link TestBag} for exercising the {@link PredicatedBag} * implementation. * * @author Matt Hall, John Watkinson, Phil Steitz * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:44 $ * @since Commons Collections 3.0 */ public class TestPredicatedBag extends AbstractTestBag { public TestPredicatedBag(String testName) { super(testName); } public static Test suite() { return new TestSuite(TestPredicatedBag.class); } public static void main(String args[]) { String[] testCaseName = {TestPredicatedBag.class.getName()}; junit.textui.TestRunner.main(testCaseName); } //-------------------------------------------------------------------------- protected Predicate stringPredicate() { return new Predicate() { public boolean evaluate(Object o) { return o instanceof String; } }; } protected Predicate truePredicate = PredicateUtils.truePredicate(); protected Bag decorateBag(HashBag bag, Predicate predicate) { return PredicatedBag.decorate(bag, predicate); } public Bag makeBag() { return decorateBag(new HashBag(), truePredicate); } protected Bag makeTestBag() { return decorateBag(new HashBag(), stringPredicate()); } //-------------------------------------------------------------------------- public void testlegalAddRemove() { Bag bag = makeTestBag(); assertEquals(0, bag.size()); Object[] els = new Object[]{"1", "3", "5", "7", "2", "4", "1"}; for (int i = 0; i < els.length; i++) { bag.add(els[i]); assertEquals(i + 1, bag.size()); assertEquals(true, bag.contains(els[i])); } Set set = ((PredicatedBag) bag).uniqueSet(); assertTrue("Unique set contains the first element", set.contains(els[0])); assertEquals(true, bag.remove(els[0])); set = ((PredicatedBag) bag).uniqueSet(); assertTrue("Unique set now does not contain the first element", !set.contains(els[0])); } public void testIllegalAdd() { Bag bag = makeTestBag(); Integer i = new Integer(3); try { bag.add(i); fail("Integer should fail string predicate."); } catch (IllegalArgumentException e) { // expected } assertTrue("Collection shouldn't contain illegal element", !bag.contains(i)); } public void testIllegalDecorate() { HashBag elements = new HashBag(); elements.add("one"); elements.add("two"); elements.add(new Integer(3)); elements.add("four"); try { Bag bag = decorateBag(elements, stringPredicate()); fail("Bag contains an element that should fail the predicate."); } catch (IllegalArgumentException e) { // expected } try { Bag bag = decorateBag(new HashBag(), null); fail("Expectiing IllegalArgumentException for null predicate."); } catch (IllegalArgumentException e) { // expected } } public String getCompatibilityVersion() { return "3.1"; } // public void testCreate() throws Exception { // Bag bag = makeBag(); // writeExternalFormToDisk((java.io.Serializable) bag, "D:/dev/collections15/data/test/PredicatedBag.emptyCollection.version3.1.obj"); // bag = makeBag(); // bag.add("A"); // bag.add("A"); // bag.add("B"); // bag.add("B"); // bag.add("C"); // writeExternalFormToDisk((java.io.Serializable) bag, "D:/dev/collections15/data/test/PredicatedBag.fullCollection.version3.1.obj"); // } } collections-generic-4.01/src/test/org/apache/commons/collections15/bag/TestTreeBag.java0000644000175000017500000000530710464140762031267 0ustar giovannigiovanni/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.bag; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.collections15.Bag; import org.apache.commons.collections15.SortedBag; /** * Extension of {@link TestBag} for exercising the {@link TreeBag} * implementation. * * @author Matt Hall, John Watkinson, Chuck Burdick * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:44 $ */ public class TestTreeBag extends AbstractTestBag { public TestTreeBag(String testName) { super(testName); } public static Test suite() { return new TestSuite(TestTreeBag.class); } public static void main(String args[]) { String[] testCaseName = {TestTreeBag.class.getName()}; junit.textui.TestRunner.main(testCaseName); } public Bag makeBag() { return new TreeBag(); } public SortedBag setupBag() { SortedBag bag = (SortedBag) makeBag(); bag.add("C"); bag.add("A"); bag.add("B"); bag.add("D"); return bag; } public void testOrdering() { Bag bag = setupBag(); assertEquals("Should get elements in correct order", "A", bag.toArray()[0]); assertEquals("Should get elements in correct order", "B", bag.toArray()[1]); assertEquals("Should get elements in correct order", "C", bag.toArray()[2]); assertEquals("Should get first key", "A", ((SortedBag) bag).first()); assertEquals("Should get last key", "D", ((SortedBag) bag).last()); } public String getCompatibilityVersion() { return "3"; } // public void testCreate() throws Exception { // Bag bag = makeBag(); // writeExternalFormToDisk((Serializable) bag, "D:/dev/collections15/data/test/TreeBag.emptyCollection.version3.obj"); // bag = makeBag(); // bag.add("A"); // bag.add("A"); // bag.add("B"); // bag.add("B"); // bag.add("C"); // writeExternalFormToDisk((Serializable) bag, "D:/dev/collections15/data/test/TreeBag.fullCollection.version3.obj"); // } } collections-generic-4.01/src/test/org/apache/commons/collections15/bag/TestTypedBag.java0000644000175000017500000000745210464140763031461 0ustar giovannigiovanni/* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.bag; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.collections15.Bag; import java.util.Set; /** * Extension of {@link TestBag} for exercising the {@link TypedBag} * implementation. * * @author Matt Hall, John Watkinson, Phil Steitz * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:44 $ * @since Commons Collections 3.0 */ public class TestTypedBag extends AbstractTestBag { public TestTypedBag(String testName) { super(testName); } public static Test suite() { return new TestSuite(TestTypedBag.class); } public static void main(String args[]) { String[] testCaseName = {TestTypedBag.class.getName()}; junit.textui.TestRunner.main(testCaseName); } //-------------------------------------------------------------------------- protected Class stringClass = this.getName().getClass(); private Object obj = new Object(); protected Class objectClass = obj.getClass(); protected Bag decorateBag(HashBag bag, Class claz) { return TypedBag.decorate(bag, claz); } public Bag makeBag() { return decorateBag(new HashBag(), objectClass); } protected Bag makeTestBag() { return decorateBag(new HashBag(), stringClass); } //-------------------------------------------------------------------------- public void testlegalAddRemove() { Bag bag = makeTestBag(); assertEquals(0, bag.size()); Object[] els = new Object[]{"1", "3", "5", "7", "2", "4", "1"}; for (int i = 0; i < els.length; i++) { bag.add(els[i]); assertEquals(i + 1, bag.size()); assertEquals(true, bag.contains(els[i])); } Set set = ((PredicatedBag) bag).uniqueSet(); assertTrue("Unique set contains the first element", set.contains(els[0])); assertEquals(true, bag.remove(els[0])); set = ((PredicatedBag) bag).uniqueSet(); assertTrue("Unique set now does not contain the first element", !set.contains(els[0])); } public void testIllegalAdd() { Bag bag = makeTestBag(); Integer i = new Integer(3); try { bag.add(i); fail("Integer should fail type check."); } catch (IllegalArgumentException e) { // expected } assertTrue("Collection shouldn't contain illegal element", !bag.contains(i)); } public void testIllegalDecorate() { HashBag elements = new HashBag(); elements.add("one"); elements.add("two"); elements.add(new Integer(3)); elements.add("four"); try { Bag bag = decorateBag(elements, stringClass); fail("Bag contains an element that should fail the type test."); } catch (IllegalArgumentException e) { // expected } try { Bag bag = decorateBag(new HashBag(), null); fail("Expectiing IllegalArgumentException for null predicate."); } catch (IllegalArgumentException e) { // expected } } protected boolean skipSerializedCanonicalTests() { return true; } } collections-generic-4.01/src/test/org/apache/commons/collections15/bag/AbstractTestBag.java0000644000175000017500000004150610464140756032137 0ustar giovannigiovanni/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.bag; import org.apache.commons.collections15.AbstractTestObject; import org.apache.commons.collections15.Bag; import java.io.IOException; import java.io.Serializable; import java.util.*; /** * Abstract test class for {@link org.apache.commons.collections15.Bag Bag} methods and contracts. *

                  * To use, simply extend this class, and implement * the {@link #makeBag} method. *

                  * If your bag fails one of these tests by design, * you may still use this base set of cases. Simply override the * test case (method) your bag fails. * * @author Matt Hall, John Watkinson, Chuck Burdick * @author Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:44 $ */ public abstract class AbstractTestBag extends AbstractTestObject { // TODO: this class should really extend from TestCollection, but the bag // implementations currently do not conform to the Collection interface. Once // those are fixed or at least a strategy is made for resolving the issue, this // can be changed back to extend TestCollection instead. /** * JUnit constructor. * * @param testName the test class name */ public AbstractTestBag(String testName) { super(testName); } //----------------------------------------------------------------------- /** * Return a new, empty bag to used for testing. * * @return the bag to be tested */ public abstract Bag makeBag(); /** * Implements the superclass method to return the Bag. * * @return the bag to be tested */ public Object makeObject() { return makeBag(); } //----------------------------------------------------------------------- public void testBagAdd() { Bag bag = makeBag(); bag.add("A"); assertTrue("Should contain 'A'", bag.contains("A")); assertEquals("Should have count of 1", 1, bag.getCount("A")); bag.add("A"); assertTrue("Should contain 'A'", bag.contains("A")); assertEquals("Should have count of 2", 2, bag.getCount("A")); bag.add("B"); assertTrue(bag.contains("A")); assertTrue(bag.contains("B")); } public void testBagEqualsSelf() { Bag bag = makeBag(); assertTrue(bag.equals(bag)); bag.add("elt"); assertTrue(bag.equals(bag)); bag.add("elt"); // again assertTrue(bag.equals(bag)); bag.add("elt2"); assertTrue(bag.equals(bag)); } public void testRemove() { Bag bag = makeBag(); bag.add("A"); assertEquals("Should have count of 1", 1, bag.getCount("A")); bag.remove("A"); assertEquals("Should have count of 0", 0, bag.getCount("A")); bag.add("A"); bag.add("A"); bag.add("A"); bag.add("A"); assertEquals("Should have count of 4", 4, bag.getCount("A")); bag.remove("A", 0); assertEquals("Should have count of 4", 4, bag.getCount("A")); bag.remove("A", 2); assertEquals("Should have count of 2", 2, bag.getCount("A")); bag.remove("A"); assertEquals("Should have count of 0", 0, bag.getCount("A")); } public void testRemoveAll() { Bag bag = makeBag(); bag.add("A", 2); assertEquals("Should have count of 2", 2, bag.getCount("A")); bag.add("B"); bag.add("C"); assertEquals("Should have count of 4", 4, bag.size()); List delete = new ArrayList(); delete.add("A"); delete.add("B"); bag.removeAll(delete); assertEquals("Should have count of 1", 1, bag.getCount("A")); assertEquals("Should have count of 0", 0, bag.getCount("B")); assertEquals("Should have count of 1", 1, bag.getCount("C")); assertEquals("Should have count of 2", 2, bag.size()); } public void testContains() { Bag bag = makeBag(); assertEquals("Bag does not have at least 1 'A'", false, bag.contains("A")); assertEquals("Bag does not have at least 1 'B'", false, bag.contains("B")); bag.add("A"); // bag 1A assertEquals("Bag has at least 1 'A'", true, bag.contains("A")); assertEquals("Bag does not have at least 1 'B'", false, bag.contains("B")); bag.add("A"); // bag 2A assertEquals("Bag has at least 1 'A'", true, bag.contains("A")); assertEquals("Bag does not have at least 1 'B'", false, bag.contains("B")); bag.add("B"); // bag 2A,1B assertEquals("Bag has at least 1 'A'", true, bag.contains("A")); assertEquals("Bag has at least 1 'B'", true, bag.contains("B")); } public void testContainsAll() { Bag bag = makeBag(); List known = new ArrayList(); List known1A = new ArrayList(); known1A.add("A"); List known2A = new ArrayList(); known2A.add("A"); known2A.add("A"); List known1B = new ArrayList(); known1B.add("B"); List known1A1B = new ArrayList(); known1A1B.add("A"); known1A1B.add("B"); assertEquals("Bag containsAll of empty", true, bag.containsAll(known)); assertEquals("Bag does not containsAll of 1 'A'", false, bag.containsAll(known1A)); assertEquals("Bag does not containsAll of 2 'A'", false, bag.containsAll(known2A)); assertEquals("Bag does not containsAll of 1 'B'", false, bag.containsAll(known1B)); assertEquals("Bag does not containsAll of 1 'A' 1 'B'", false, bag.containsAll(known1A1B)); bag.add("A"); // bag 1A assertEquals("Bag containsAll of empty", true, bag.containsAll(known)); assertEquals("Bag containsAll of 1 'A'", true, bag.containsAll(known1A)); assertEquals("Bag does not containsAll of 2 'A'", false, bag.containsAll(known2A)); assertEquals("Bag does not containsAll of 1 'B'", false, bag.containsAll(known1B)); assertEquals("Bag does not containsAll of 1 'A' 1 'B'", false, bag.containsAll(known1A1B)); bag.add("A"); // bag 2A assertEquals("Bag containsAll of empty", true, bag.containsAll(known)); assertEquals("Bag containsAll of 1 'A'", true, bag.containsAll(known1A)); assertEquals("Bag containsAll of 2 'A'", true, bag.containsAll(known2A)); assertEquals("Bag does not containsAll of 1 'B'", false, bag.containsAll(known1B)); assertEquals("Bag does not containsAll of 1 'A' 1 'B'", false, bag.containsAll(known1A1B)); bag.add("A"); // bag 3A assertEquals("Bag containsAll of empty", true, bag.containsAll(known)); assertEquals("Bag containsAll of 1 'A'", true, bag.containsAll(known1A)); assertEquals("Bag containsAll of 2 'A'", true, bag.containsAll(known2A)); assertEquals("Bag does not containsAll of 1 'B'", false, bag.containsAll(known1B)); assertEquals("Bag does not containsAll of 1 'A' 1 'B'", false, bag.containsAll(known1A1B)); bag.add("B"); // bag 3A1B assertEquals("Bag containsAll of empty", true, bag.containsAll(known)); assertEquals("Bag containsAll of 1 'A'", true, bag.containsAll(known1A)); assertEquals("Bag containsAll of 2 'A'", true, bag.containsAll(known2A)); assertEquals("Bag containsAll of 1 'B'", true, bag.containsAll(known1B)); assertEquals("Bag containsAll of 1 'A' 1 'B'", true, bag.containsAll(known1A1B)); } public void testSize() { Bag bag = makeBag(); assertEquals("Should have 0 total items", 0, bag.size()); bag.add("A"); assertEquals("Should have 1 total items", 1, bag.size()); bag.add("A"); assertEquals("Should have 2 total items", 2, bag.size()); bag.add("A"); assertEquals("Should have 3 total items", 3, bag.size()); bag.add("B"); assertEquals("Should have 4 total items", 4, bag.size()); bag.add("B"); assertEquals("Should have 5 total items", 5, bag.size()); bag.remove("A", 2); assertEquals("Should have 1 'A'", 1, bag.getCount("A")); assertEquals("Should have 3 total items", 3, bag.size()); bag.remove("B"); assertEquals("Should have 1 total item", 1, bag.size()); } public void testRetainAll() { Bag bag = makeBag(); bag.add("A"); bag.add("A"); bag.add("A"); bag.add("B"); bag.add("B"); bag.add("C"); List retains = new ArrayList(); retains.add("B"); retains.add("C"); bag.retainAll(retains); assertEquals("Should have 2 total items", 2, bag.size()); } public void testIterator() { Bag bag = makeBag(); bag.add("A"); bag.add("A"); bag.add("B"); assertEquals("Bag should have 3 items", 3, bag.size()); Iterator i = bag.iterator(); boolean foundA = false; while (i.hasNext()) { String element = (String) i.next(); // ignore the first A, remove the second via Iterator.remove() if (element.equals("A")) { if (foundA == false) { foundA = true; } else { i.remove(); } } } assertTrue("Bag should still contain 'A'", bag.contains("A")); assertEquals("Bag should have 2 items", 2, bag.size()); assertEquals("Bag should have 1 'A'", 1, bag.getCount("A")); } public void testIteratorFail() { Bag bag = makeBag(); bag.add("A"); bag.add("A"); bag.add("B"); Iterator it = bag.iterator(); it.next(); bag.remove("A"); try { it.next(); fail("Should throw ConcurrentModificationException"); } catch (ConcurrentModificationException e) { // expected } } public void testIteratorFailNoMore() { Bag bag = makeBag(); bag.add("A"); bag.add("A"); bag.add("B"); Iterator it = bag.iterator(); it.next(); it.next(); it.next(); try { it.next(); fail("Should throw NoSuchElementException"); } catch (NoSuchElementException ex) { // expected } } public void testIteratorFailDoubleRemove() { Bag bag = makeBag(); bag.add("A"); bag.add("A"); bag.add("B"); Iterator it = bag.iterator(); it.next(); it.next(); assertEquals(3, bag.size()); it.remove(); assertEquals(2, bag.size()); try { it.remove(); fail("Should throw IllegalStateException"); } catch (IllegalStateException ex) { // expected } assertEquals(2, bag.size()); it.next(); it.remove(); assertEquals(1, bag.size()); } public void testToArray() { Bag bag = makeBag(); bag.add("A"); bag.add("A"); bag.add("B"); bag.add("B"); bag.add("C"); Object[] array = bag.toArray(); int a = 0, b = 0, c = 0; for (int i = 0; i < array.length; i++) { a += (array[i].equals("A") ? 1 : 0); b += (array[i].equals("B") ? 1 : 0); c += (array[i].equals("C") ? 1 : 0); } assertEquals(2, a); assertEquals(2, b); assertEquals(1, c); } public void testToArrayPopulate() { Bag bag = makeBag(); bag.add("A"); bag.add("A"); bag.add("B"); bag.add("B"); bag.add("C"); String[] array = (String[]) bag.toArray(new String[0]); int a = 0, b = 0, c = 0; for (int i = 0; i < array.length; i++) { a += (array[i].equals("A") ? 1 : 0); b += (array[i].equals("B") ? 1 : 0); c += (array[i].equals("C") ? 1 : 0); } assertEquals(2, a); assertEquals(2, b); assertEquals(1, c); } //----------------------------------------------------------------------- public void testEquals() { Bag bag = makeBag(); Bag bag2 = makeBag(); assertEquals(true, bag.equals(bag2)); bag.add("A"); assertEquals(false, bag.equals(bag2)); bag2.add("A"); assertEquals(true, bag.equals(bag2)); bag.add("A"); bag.add("B"); bag.add("B"); bag.add("C"); bag2.add("A"); bag2.add("B"); bag2.add("B"); bag2.add("C"); assertEquals(true, bag.equals(bag2)); } public void testEqualsHashBag() { Bag bag = makeBag(); Bag bag2 = new HashBag(); assertEquals(true, bag.equals(bag2)); bag.add("A"); assertEquals(false, bag.equals(bag2)); bag2.add("A"); assertEquals(true, bag.equals(bag2)); bag.add("A"); bag.add("B"); bag.add("B"); bag.add("C"); bag2.add("A"); bag2.add("B"); bag2.add("B"); bag2.add("C"); assertEquals(true, bag.equals(bag2)); } public void testHashCode() { Bag bag = makeBag(); Bag bag2 = makeBag(); assertEquals(0, bag.hashCode()); assertEquals(0, bag2.hashCode()); assertEquals(bag.hashCode(), bag2.hashCode()); bag.add("A"); bag.add("A"); bag.add("B"); bag.add("B"); bag.add("C"); bag2.add("A"); bag2.add("A"); bag2.add("B"); bag2.add("B"); bag2.add("C"); assertEquals(bag.hashCode(), bag2.hashCode()); int total = 0; total += ("A".hashCode() ^ 2); total += ("B".hashCode() ^ 2); total += ("C".hashCode() ^ 1); assertEquals(total, bag.hashCode()); assertEquals(total, bag2.hashCode()); } //----------------------------------------------------------------------- public void testEmptyBagSerialization() throws IOException, ClassNotFoundException { Bag bag = makeBag(); if (!(bag instanceof Serializable && isTestSerialization())) return; byte[] objekt = writeExternalFormToBytes((Serializable) bag); Bag bag2 = (Bag) readExternalFormFromBytes(objekt); assertEquals("Bag should be empty", 0, bag.size()); assertEquals("Bag should be empty", 0, bag2.size()); } public void testFullBagSerialization() throws IOException, ClassNotFoundException { Bag bag = makeBag(); bag.add("A"); bag.add("A"); bag.add("B"); bag.add("B"); bag.add("C"); int size = bag.size(); if (!(bag instanceof Serializable && isTestSerialization())) return; byte[] objekt = writeExternalFormToBytes((Serializable) bag); Bag bag2 = (Bag) readExternalFormFromBytes(objekt); assertEquals("Bag should be same size", size, bag.size()); assertEquals("Bag should be same size", size, bag2.size()); } /** * Compare the current serialized form of the Bag * against the canonical version in CVS. */ public void testEmptyBagCompatibility() throws IOException, ClassNotFoundException { // test to make sure the canonical form has been preserved // Disabled as binary compatibility with 3.0 is not supported. // Bag bag = makeBag(); // if (bag instanceof Serializable && !skipSerializedCanonicalTests() && isTestSerialization()) { // Bag bag2 = (Bag) readExternalFormFromDisk(getCanonicalEmptyCollectionName(bag)); // assertTrue("Bag is empty", bag2.size() == 0); // assertEquals(bag, bag2); // } } /** * Compare the current serialized form of the Bag * against the canonical version in CVS. */ public void testFullBagCompatibility() throws IOException, ClassNotFoundException { // test to make sure the canonical form has been preserved // Disabled as binary compatibility with 3.0 is not supported. // Bag bag = makeBag(); // bag.add("A"); // bag.add("A"); // bag.add("B"); // bag.add("B"); // bag.add("C"); // if (bag instanceof Serializable && !skipSerializedCanonicalTests() && isTestSerialization()) { // Bag bag2 = (Bag) readExternalFormFromDisk(getCanonicalFullCollectionName(bag)); // assertEquals("Bag is the right size", bag.size(), bag2.size()); // assertEquals(bag, bag2); // } } } collections-generic-4.01/src/test/org/apache/commons/collections15/bag/TestAll.java0000644000175000017500000000331410464140754030463 0ustar giovannigiovanni/* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.bag; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * Entry point for tests. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:44 $ * @since Commons Collections 3.0 */ public class TestAll extends TestCase { public TestAll(String testName) { super(testName); } public static void main(String args[]) { String[] testCaseName = {TestAll.class.getName()}; junit.textui.TestRunner.main(testCaseName); } public static Test suite() { TestSuite suite = new TestSuite(); suite.addTest(TestHashBag.suite()); suite.addTest(TestPredicatedBag.suite()); suite.addTest(TestPredicatedSortedBag.suite()); suite.addTest(TestTransformedBag.suite()); suite.addTest(TestTransformedSortedBag.suite()); suite.addTest(TestTreeBag.suite()); suite.addTest(TestTypedBag.suite()); suite.addTest(TestTypedSortedBag.suite()); return suite; } } collections-generic-4.01/src/test/org/apache/commons/collections15/bag/AbstractTestSortedBag.java0000644000175000017500000000220010464140763033302 0ustar giovannigiovanni/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.bag; /** * Abstract test class for * {@link org.apache.commons.collections15.SortedBag SortedBag} * methods and contracts. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:44 $ * @since Commons Collections 3.0 */ public abstract class AbstractTestSortedBag extends AbstractTestBag { public AbstractTestSortedBag(String testName) { super(testName); } // TODO: Add the SortedBag tests! } collections-generic-4.01/src/test/org/apache/commons/collections15/TestEnumerationUtils.java0000644000175000017500000000665710464140755032547 0ustar giovannigiovanni/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15; import junit.framework.Assert; import junit.framework.Test; import java.util.ArrayList; import java.util.Hashtable; import java.util.List; import java.util.StringTokenizer; /** * Tests EnumerationUtils. * * @author Matt Hall, John Watkinson, Gary Gregory * @version $Id: TestEnumerationUtils.java,v 1.1 2005/10/11 17:05:39 pents90 Exp $ */ public class TestEnumerationUtils extends BulkTest { public TestEnumerationUtils(String name) { super(name); } public static final String TO_LIST_FIXTURE = "this is a test"; public void testToListWithStringTokenizer() { List expectedList1 = new ArrayList(); StringTokenizer st = new StringTokenizer(TO_LIST_FIXTURE); while (st.hasMoreTokens()) { expectedList1.add(st.nextToken()); } List expectedList2 = new ArrayList(); expectedList2.add("this"); expectedList2.add("is"); expectedList2.add("a"); expectedList2.add("test"); List actualList = EnumerationUtils.toList(new StringTokenizer(TO_LIST_FIXTURE)); Assert.assertEquals(expectedList1, expectedList2); Assert.assertEquals(expectedList1, actualList); Assert.assertEquals(expectedList2, actualList); } public void testToListWithHashtable() { Hashtable expected = new Hashtable(); expected.put("one", new Integer(1)); expected.put("two", new Integer(2)); expected.put("three", new Integer(3)); // validate elements. List actualEltList = EnumerationUtils.toList(expected.elements()); Assert.assertEquals(expected.size(), actualEltList.size()); Assert.assertTrue(actualEltList.contains(new Integer(1))); Assert.assertTrue(actualEltList.contains(new Integer(2))); Assert.assertTrue(actualEltList.contains(new Integer(3))); List expectedEltList = new ArrayList(); expectedEltList.add(new Integer(1)); expectedEltList.add(new Integer(2)); expectedEltList.add(new Integer(3)); Assert.assertTrue(actualEltList.containsAll(expectedEltList)); // validate keys. List actualKeyList = EnumerationUtils.toList(expected.keys()); Assert.assertEquals(expected.size(), actualEltList.size()); Assert.assertTrue(actualKeyList.contains("one")); Assert.assertTrue(actualKeyList.contains("two")); Assert.assertTrue(actualKeyList.contains("three")); List expectedKeyList = new ArrayList(); expectedKeyList.add("one"); expectedKeyList.add("two"); expectedKeyList.add("three"); Assert.assertTrue(actualKeyList.containsAll(expectedKeyList)); } public static Test suite() { return BulkTest.makeSuite(TestEnumerationUtils.class); } } collections-generic-4.01/src/test/org/apache/commons/collections15/TestExtendedProperties.java0000644000175000017500000002212010464140765033035 0ustar giovannigiovanni/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; /** * Tests some basic functions of the ExtendedProperties class. * * @author Geir Magnusson Jr. * @author Mohan Kishore * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:39 $ */ public class TestExtendedProperties extends TestCase { protected ExtendedProperties eprop = new ExtendedProperties(); public TestExtendedProperties(String testName) { super(testName); } public static Test suite() { return new TestSuite(TestExtendedProperties.class); } public static void main(String args[]) { String[] testCaseName = {TestExtendedProperties.class.getName()}; junit.textui.TestRunner.main(testCaseName); } public void testRetrieve() { /* * should be empty and return null */ assertEquals("This returns null", eprop.getProperty("foo"), null); /* * add a real value, and get it two different ways */ eprop.setProperty("number", "1"); assertEquals("This returns '1'", eprop.getProperty("number"), "1"); assertEquals("This returns '1'", eprop.getString("number"), "1"); /* * now add another and get a Vector */ eprop.addProperty("number", "2"); assertTrue("This returns array", (eprop.getVector("number") instanceof java.util.Vector)); /* * now test dan's new fix where we get the first scalar * when we access a vector valued * property */ assertTrue("This returns scalar", (eprop.getString("number") instanceof String)); /* * test comma separated string properties */ String prop = "hey, that's a test"; eprop.setProperty("prop.string", prop); assertTrue("This returns vector", (eprop.getVector("prop.string") instanceof java.util.Vector)); String prop2 = "hey\\, that's a test"; eprop.remove("prop.string"); eprop.setProperty("prop.string", prop2); assertTrue("This returns array", (eprop.getString("prop.string") instanceof java.lang.String)); /* * test subset : we want to make sure that the EP doesn't reprocess the data * elements when generating the subset */ ExtendedProperties subEprop = eprop.subset("prop"); assertTrue("Returns the full string", subEprop.getString("string").equals(prop)); assertTrue("This returns string for subset", (subEprop.getString("string") instanceof java.lang.String)); assertTrue("This returns array for subset", (subEprop.getVector("string") instanceof java.util.Vector)); } public void testInterpolation() { eprop.setProperty("applicationRoot", "/home/applicationRoot"); eprop.setProperty("db", "${applicationRoot}/db/hypersonic"); String dbProp = "/home/applicationRoot/db/hypersonic"; assertTrue("Checking interpolated variable", eprop.getString("db").equals(dbProp)); } public void testSaveAndLoad() { ExtendedProperties ep1 = new ExtendedProperties(); ExtendedProperties ep2 = new ExtendedProperties(); try { /* initialize value: one=Hello\World two=Hello\,World three=Hello,World */ String s1 = "one=Hello\\World\ntwo=Hello\\,World\nthree=Hello,World"; byte[] bytes = s1.getBytes(); ByteArrayInputStream bais = new ByteArrayInputStream(bytes); ep1.load(bais); assertEquals("Back-slashes not interpreted properly", "Hello\\World", ep1.getString("one")); assertEquals("Escaped commas not interpreted properly", "Hello,World", ep1.getString("two")); assertEquals("Commas not interpreted properly", 2, ep1.getVector("three").size()); assertEquals("Commas not interpreted properly", "Hello", ep1.getVector("three").get(0)); assertEquals("Commas not interpreted properly", "World", ep1.getVector("three").get(1)); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ep1.save(baos, null); bytes = baos.toByteArray(); bais = new ByteArrayInputStream(bytes); ep2.load(bais); assertEquals("Back-slash not same after being saved and loaded", ep1.getString("one"), ep2.getString("one")); assertEquals("Escaped comma not same after being saved and loaded", ep1.getString("two"), ep2.getString("two")); assertEquals("Comma not same after being saved and loaded", ep1.getString("three"), ep2.getString("three")); } catch (IOException ioe) { fail("There was an exception saving and loading the EP"); } } public void testTrailingBackSlash() { ExtendedProperties ep1 = new ExtendedProperties(); try { /* initialize using: one=ONE two=TWO \\ three=THREE */ String s1 = "one=ONE\ntwo=TWO \\\\\nthree=THREE"; byte[] bytes = s1.getBytes(); ByteArrayInputStream bais = new ByteArrayInputStream(bytes); ep1.load(bais); assertEquals("Trailing back-slashes not interpreted properly", 3, ep1.size()); assertEquals("Back-slash not escaped properly", "TWO \\", ep1.getString("two")); } catch (IOException ioe) { fail("There was an exception loading the EP"); } } public void testMultipleSameKey1() throws Exception { ExtendedProperties ep1 = new ExtendedProperties(); /* initialize using: one=a one=b,c */ String s1 = "one=a\none=b,c\n"; byte[] bytes = s1.getBytes(); ByteArrayInputStream bais = new ByteArrayInputStream(bytes); ep1.load(bais); assertEquals(1, ep1.size()); assertEquals(3, ep1.getVector("one").size()); assertEquals("a", ep1.getVector("one").get(0)); assertEquals("b", ep1.getVector("one").get(1)); assertEquals("c", ep1.getVector("one").get(2)); } public void testMultipleSameKey2() throws Exception { ExtendedProperties ep1 = new ExtendedProperties(); /* initialize using: one=a,b one=c,d */ String s1 = "one=a,b\none=c,d\n"; byte[] bytes = s1.getBytes(); ByteArrayInputStream bais = new ByteArrayInputStream(bytes); ep1.load(bais); assertEquals(1, ep1.size()); assertEquals(4, ep1.getVector("one").size()); assertEquals("a", ep1.getVector("one").get(0)); assertEquals("b", ep1.getVector("one").get(1)); assertEquals("c", ep1.getVector("one").get(2)); assertEquals("d", ep1.getVector("one").get(3)); } public void testMultipleSameKey3() throws Exception { ExtendedProperties ep1 = new ExtendedProperties(); /* initialize using: one=a,b one=c */ String s1 = "one=a,b\none=c\n"; byte[] bytes = s1.getBytes(); ByteArrayInputStream bais = new ByteArrayInputStream(bytes); ep1.load(bais); assertEquals(1, ep1.size()); assertEquals(3, ep1.getVector("one").size()); assertEquals("a", ep1.getVector("one").get(0)); assertEquals("b", ep1.getVector("one").get(1)); assertEquals("c", ep1.getVector("one").get(2)); } public void testMultipleSameKeyByCode() throws Exception { ExtendedProperties ep1 = new ExtendedProperties(); ep1.addProperty("one", "a"); assertEquals(1, ep1.size()); assertEquals(1, ep1.getVector("one").size()); assertEquals("a", ep1.getVector("one").get(0)); ep1.addProperty("one", Boolean.TRUE); assertEquals(1, ep1.size()); assertEquals(2, ep1.getVector("one").size()); assertEquals("a", ep1.getVector("one").get(0)); assertEquals(Boolean.TRUE, ep1.getVector("one").get(1)); ep1.addProperty("one", "c,d"); assertEquals(1, ep1.size()); assertEquals(4, ep1.getVector("one").size()); assertEquals("a", ep1.getVector("one").get(0)); assertEquals(Boolean.TRUE, ep1.getVector("one").get(1)); assertEquals("c", ep1.getVector("one").get(2)); assertEquals("d", ep1.getVector("one").get(3)); } } collections-generic-4.01/src/test/org/apache/commons/collections15/TestFastHashMap1.java0000644000175000017500000000307410464140756031447 0ustar giovannigiovanni/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15; import junit.framework.Test; import java.util.HashMap; import java.util.Map; import org.apache.commons.collections15.map.FastHashMap; /** * Test FastHashMap in fast mode. * * @author Matt Hall, John Watkinson, Jason van Zyl * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:39 $ */ public class TestFastHashMap1 extends TestFastHashMap { public TestFastHashMap1(String testName) { super(testName); } public static Test suite() { return BulkTest.makeSuite(TestFastHashMap1.class); } public static void main(String args[]) { String[] testCaseName = {TestFastHashMap1.class.getName()}; junit.textui.TestRunner.main(testCaseName); } public Map makeEmptyMap() { FastHashMap fhm = new FastHashMap(); fhm.setFast(true); return (fhm); } public void setUp() { map = (HashMap) makeEmptyMap(); } } collections-generic-4.01/src/test/org/apache/commons/collections15/TestClosureUtils.java0000644000175000017500000003230010464140754031654 0ustar giovannigiovanni/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15; import junit.framework.Test; import junit.framework.TestSuite; import junit.textui.TestRunner; import org.apache.commons.collections15.functors.NOPClosure; import java.util.*; /** * Tests the org.apache.commons.collections15.ClosureUtils class. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:39 $ * @since Commons Collections 3.0 */ public class TestClosureUtils extends junit.framework.TestCase { private static final Object cObject = new Object(); private static final Object cString = "Hello"; private static final Object cInteger = new Integer(6); /** * Construct */ public TestClosureUtils(String name) { super(name); } /** * Main. * * @param args */ public static void main(String[] args) { TestRunner.run(suite()); } /** * Return class as a test suite. */ public static Test suite() { return new TestSuite(TestClosureUtils.class); } /** * Set up instance variables required by this test case. */ public void setUp() { } /** * Tear down instance variables required by this test case. */ public void tearDown() { } static class MockClosure implements Closure { int count = 0; public void execute(Object object) { count++; } } static class MockTransformer implements Transformer { int count = 0; public Object transform(Object object) { count++; return object; } } // exceptionClosure //------------------------------------------------------------------ public void testExceptionClosure() { assertNotNull(ClosureUtils.exceptionClosure()); assertSame(ClosureUtils.exceptionClosure(), ClosureUtils.exceptionClosure()); try { ClosureUtils.exceptionClosure().execute(null); } catch (FunctorException ex) { try { ClosureUtils.exceptionClosure().execute(cString); } catch (FunctorException ex2) { return; } } fail(); } // nopClosure //------------------------------------------------------------------ public void testNopClosure() { StringBuffer buf = new StringBuffer("Hello"); ClosureUtils.nopClosure().execute(null); assertEquals("Hello", buf.toString()); ClosureUtils.nopClosure().execute("Hello"); assertEquals("Hello", buf.toString()); } // invokeClosure //------------------------------------------------------------------ public void testInvokeClosure() { StringBuffer buf = new StringBuffer("Hello"); ClosureUtils.invokerClosure("reverse").execute(buf); assertEquals("olleH", buf.toString()); buf = new StringBuffer("Hello"); ClosureUtils.invokerClosure("setLength", new Class[]{Integer.TYPE}, new Object[]{new Integer(2)}).execute(buf); assertEquals("He", buf.toString()); } // forClosure //------------------------------------------------------------------ public void testForClosure() { MockClosure cmd = new MockClosure(); ClosureUtils.forClosure(5, cmd).execute(null); assertEquals(5, cmd.count); assertSame(NOPClosure.INSTANCE, ClosureUtils.forClosure(0, new MockClosure())); assertSame(NOPClosure.INSTANCE, ClosureUtils.forClosure(-1, new MockClosure())); assertSame(NOPClosure.INSTANCE, ClosureUtils.forClosure(1, null)); assertSame(NOPClosure.INSTANCE, ClosureUtils.forClosure(3, null)); assertSame(cmd, ClosureUtils.forClosure(1, cmd)); } // whileClosure //------------------------------------------------------------------ public void testWhileClosure() { MockClosure cmd = new MockClosure(); ClosureUtils.whileClosure(PredicateUtils.falsePredicate(), cmd).execute(null); assertEquals(0, cmd.count); cmd = new MockClosure(); ClosureUtils.whileClosure(PredicateUtils.uniquePredicate(), cmd).execute(null); assertEquals(1, cmd.count); try { ClosureUtils.whileClosure(null, ClosureUtils.nopClosure()); fail(); } catch (IllegalArgumentException ex) { } try { ClosureUtils.whileClosure(PredicateUtils.falsePredicate(), null); fail(); } catch (IllegalArgumentException ex) { } try { ClosureUtils.whileClosure(null, null); fail(); } catch (IllegalArgumentException ex) { } } // doWhileClosure //------------------------------------------------------------------ public void testDoWhileClosure() { MockClosure cmd = new MockClosure(); ClosureUtils.doWhileClosure(cmd, PredicateUtils.falsePredicate()).execute(null); assertEquals(1, cmd.count); cmd = new MockClosure(); ClosureUtils.doWhileClosure(cmd, PredicateUtils.uniquePredicate()).execute(null); assertEquals(2, cmd.count); try { ClosureUtils.doWhileClosure(null, null); fail(); } catch (IllegalArgumentException ex) { } } // chainedClosure //------------------------------------------------------------------ public void testChainedClosure() { MockClosure a = new MockClosure(); MockClosure b = new MockClosure(); ClosureUtils.chainedClosure(a, b).execute(null); assertEquals(1, a.count); assertEquals(1, b.count); a = new MockClosure(); b = new MockClosure(); ClosureUtils.chainedClosure(new Closure[]{a, b, a}).execute(null); assertEquals(2, a.count); assertEquals(1, b.count); a = new MockClosure(); b = new MockClosure(); Collection coll = new ArrayList(); coll.add(b); coll.add(a); coll.add(b); ClosureUtils.chainedClosure(coll).execute(null); assertEquals(1, a.count); assertEquals(2, b.count); assertSame(NOPClosure.INSTANCE, ClosureUtils.chainedClosure(new Closure[0])); assertSame(NOPClosure.INSTANCE, ClosureUtils.chainedClosure(Collections.EMPTY_LIST)); try { ClosureUtils.chainedClosure(null, null); fail(); } catch (IllegalArgumentException ex) { } try { ClosureUtils.chainedClosure((Closure[]) null); fail(); } catch (IllegalArgumentException ex) { } try { ClosureUtils.chainedClosure((Collection) null); fail(); } catch (IllegalArgumentException ex) { } try { ClosureUtils.chainedClosure(new Closure[]{null, null}); fail(); } catch (IllegalArgumentException ex) { } try { coll = new ArrayList(); coll.add(null); coll.add(null); ClosureUtils.chainedClosure(coll); fail(); } catch (IllegalArgumentException ex) { } } // switchClosure //------------------------------------------------------------------ public void testSwitchClosure() { MockClosure a = new MockClosure(); MockClosure b = new MockClosure(); ClosureUtils.ifClosure(PredicateUtils.truePredicate(), a, b).execute(null); assertEquals(1, a.count); assertEquals(0, b.count); a = new MockClosure(); b = new MockClosure(); ClosureUtils.ifClosure(PredicateUtils.falsePredicate(), a, b).execute(null); assertEquals(0, a.count); assertEquals(1, b.count); a = new MockClosure(); b = new MockClosure(); ClosureUtils.switchClosure(new Predicate[]{PredicateUtils.equalPredicate("HELLO"), PredicateUtils.equalPredicate("THERE")}, new Closure[]{a, b}).execute("WELL"); assertEquals(0, a.count); assertEquals(0, b.count); a = new MockClosure(); b = new MockClosure(); ClosureUtils.switchClosure(new Predicate[]{PredicateUtils.equalPredicate("HELLO"), PredicateUtils.equalPredicate("THERE")}, new Closure[]{a, b}).execute("HELLO"); assertEquals(1, a.count); assertEquals(0, b.count); a = new MockClosure(); b = new MockClosure(); MockClosure c = new MockClosure(); ClosureUtils.switchClosure(new Predicate[]{PredicateUtils.equalPredicate("HELLO"), PredicateUtils.equalPredicate("THERE")}, new Closure[]{a, b}, c).execute("WELL"); assertEquals(0, a.count); assertEquals(0, b.count); assertEquals(1, c.count); a = new MockClosure(); b = new MockClosure(); Map map = new HashMap(); map.put(PredicateUtils.equalPredicate("HELLO"), a); map.put(PredicateUtils.equalPredicate("THERE"), b); ClosureUtils.switchClosure(map).execute(null); assertEquals(0, a.count); assertEquals(0, b.count); a = new MockClosure(); b = new MockClosure(); map = new HashMap(); map.put(PredicateUtils.equalPredicate("HELLO"), a); map.put(PredicateUtils.equalPredicate("THERE"), b); ClosureUtils.switchClosure(map).execute("THERE"); assertEquals(0, a.count); assertEquals(1, b.count); a = new MockClosure(); b = new MockClosure(); c = new MockClosure(); map = new HashMap(); map.put(PredicateUtils.equalPredicate("HELLO"), a); map.put(PredicateUtils.equalPredicate("THERE"), b); map.put(null, c); ClosureUtils.switchClosure(map).execute("WELL"); assertEquals(0, a.count); assertEquals(0, b.count); assertEquals(1, c.count); assertSame(NOPClosure.INSTANCE, ClosureUtils.switchClosure(new Predicate[0], new Closure[0])); assertSame(NOPClosure.INSTANCE, ClosureUtils.switchClosure(new HashMap())); map = new HashMap(); map.put(null, null); assertSame(NOPClosure.INSTANCE, ClosureUtils.switchClosure(map)); try { ClosureUtils.switchClosure(null, null); fail(); } catch (IllegalArgumentException ex) { } try { ClosureUtils.switchClosure((Predicate[]) null, (Closure[]) null); fail(); } catch (IllegalArgumentException ex) { } try { ClosureUtils.switchClosure((Map) null); fail(); } catch (IllegalArgumentException ex) { } try { ClosureUtils.switchClosure(new Predicate[2], new Closure[2]); fail(); } catch (IllegalArgumentException ex) { } try { ClosureUtils.switchClosure(new Predicate[]{PredicateUtils.truePredicate()}, new Closure[]{a, b}); fail(); } catch (IllegalArgumentException ex) { } } // switchMapClosure //------------------------------------------------------------------ public void testSwitchMapClosure() { MockClosure a = new MockClosure(); MockClosure b = new MockClosure(); Map map = new HashMap(); map.put("HELLO", a); map.put("THERE", b); ClosureUtils.switchMapClosure(map).execute(null); assertEquals(0, a.count); assertEquals(0, b.count); a = new MockClosure(); b = new MockClosure(); map = new HashMap(); map.put("HELLO", a); map.put("THERE", b); ClosureUtils.switchMapClosure(map).execute("THERE"); assertEquals(0, a.count); assertEquals(1, b.count); a = new MockClosure(); b = new MockClosure(); MockClosure c = new MockClosure(); map = new HashMap(); map.put("HELLO", a); map.put("THERE", b); map.put(null, c); ClosureUtils.switchMapClosure(map).execute("WELL"); assertEquals(0, a.count); assertEquals(0, b.count); assertEquals(1, c.count); assertSame(NOPClosure.INSTANCE, ClosureUtils.switchMapClosure(new HashMap())); try { ClosureUtils.switchMapClosure(null); fail(); } catch (IllegalArgumentException ex) { } } // asClosure //------------------------------------------------------------------ public void testTransformerClosure() { MockTransformer mock = new MockTransformer(); Closure closure = ClosureUtils.asClosure(mock); closure.execute(null); assertEquals(1, mock.count); closure.execute(null); assertEquals(2, mock.count); assertSame(ClosureUtils.nopClosure(), ClosureUtils.asClosure(null)); } } collections-generic-4.01/src/test/org/apache/commons/collections15/TestBufferUtils.java0000644000175000017500000000400310464140762031447 0ustar giovannigiovanni/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15; import junit.framework.Test; import org.apache.commons.collections15.buffer.PredicatedBuffer; /** * Tests for BufferUtils. * * @author Matt Hall, John Watkinson, Unknown * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:39 $ */ public class TestBufferUtils extends BulkTest { public TestBufferUtils(String name) { super(name); } public static Test suite() { return BulkTest.makeSuite(TestBufferUtils.class); } public void testNothing() { } public void testpredicatedBuffer() { Predicate predicate = new Predicate() { public boolean evaluate(Object o) { return o instanceof String; } }; Buffer buffer = BufferUtils.predicatedBuffer(new ArrayStack(), predicate); assertTrue("returned object should be a PredicatedBuffer", buffer instanceof PredicatedBuffer); try { buffer = BufferUtils.predicatedBuffer(new ArrayStack(), null); fail("Expecting IllegalArgumentException for null predicate."); } catch (IllegalArgumentException ex) { // expected } try { buffer = BufferUtils.predicatedBuffer(null, predicate); fail("Expecting IllegalArgumentException for null buffer."); } catch (IllegalArgumentException ex) { // expected } } } collections-generic-4.01/src/test/org/apache/commons/collections15/TestArrayList.java0000644000175000017500000000424310464140754031136 0ustar giovannigiovanni/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.collections15.list.AbstractTestList; import java.util.ArrayList; /** * Abstract test class for ArrayList. * * @author Matt Hall, John Watkinson, Jason van Zyl * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:39 $ */ public abstract class TestArrayList extends AbstractTestList { protected ArrayList list = null; public TestArrayList(String testName) { super(testName); } public static Test suite() { return new TestSuite(TestArrayList.class); } public static void main(String args[]) { String[] testCaseName = {TestArrayList.class.getName()}; junit.textui.TestRunner.main(testCaseName); } public void setUp() { list = (ArrayList) makeEmptyList(); } //----------------------------------------------------------------------- public void testNewArrayList() { assertTrue("New list is empty", list.isEmpty()); assertEquals("New list has size zero", list.size(), 0); try { list.get(1); fail("get(int i) should have thrown IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { ; // Expected result } } public void testSearch() { list.add("First Item"); list.add("Last Item"); assertEquals("First item is 'First Item'", list.get(0), "First Item"); assertEquals("Last Item is 'Last Item'", list.get(1), "Last Item"); } } collections-generic-4.01/src/test/org/apache/commons/collections15/AbstractTestObject.java0000644000175000017500000002622510464140761032120 0ustar giovannigiovanni/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15; import java.io.*; /** * Abstract test class for {@link java.lang.Object} methods and contracts. *

                  * To use, simply extend this class, and implement * the {@link #makeObject()} method. *

                  * If your {@link Object} fails one of these tests by design, * you may still use this base set of cases. Simply override the * test case (method) your {@link Object} fails. * * @author Rodney Waldhoff * @author Stephen Colebourne * @author Matt Hall, John Watkinson, Anonymous * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:39 $ */ public abstract class AbstractTestObject extends BulkTest { /** * Current major release for Collections */ public static final int COLLECTIONS_MAJOR_VERSION = 3; /** * JUnit constructor. * * @param testName the test class name */ public AbstractTestObject(String testName) { super(testName); } //----------------------------------------------------------------------- /** * Implement this method to return the object to test. * * @return the object to test */ public abstract Object makeObject(); /** * Override this method if a subclass is testing an object * that cannot serialize an "empty" Collection. * (e.g. Comparators have no contents) * * @return true */ public boolean supportsEmptyCollections() { return true; } /** * Override this method if a subclass is testing an object * that cannot serialize a "full" Collection. * (e.g. Comparators have no contents) * * @return true */ public boolean supportsFullCollections() { return true; } /** * Is serialization testing supported. * Default is true. */ public boolean isTestSerialization() { return true; } /** * Returns true to indicate that the collection supports equals() comparisons. * This implementation returns true; */ public boolean isEqualsCheckable() { return true; } //----------------------------------------------------------------------- public void testObjectEqualsSelf() { Object obj = makeObject(); assertEquals("A Object should equal itself", obj, obj); } public void testEqualsNull() { Object obj = makeObject(); assertEquals(false, obj.equals(null)); // make sure this doesn't throw NPE either } public void testObjectHashCodeEqualsSelfHashCode() { Object obj = makeObject(); assertEquals("hashCode should be repeatable", obj.hashCode(), obj.hashCode()); } public void testObjectHashCodeEqualsContract() { Object obj1 = makeObject(); if (obj1.equals(obj1)) { assertEquals("[1] When two objects are equal, their hashCodes should be also.", obj1.hashCode(), obj1.hashCode()); } Object obj2 = makeObject(); if (obj1.equals(obj2)) { assertEquals("[2] When two objects are equal, their hashCodes should be also.", obj1.hashCode(), obj2.hashCode()); assertTrue("When obj1.equals(obj2) is true, then obj2.equals(obj1) should also be true", obj2.equals(obj1)); } } public void testSerializeDeserializeThenCompare() throws Exception { Object obj = makeObject(); if (obj instanceof Serializable && isTestSerialization()) { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(buffer); out.writeObject(obj); out.close(); ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(buffer.toByteArray())); Object dest = in.readObject(); in.close(); if (isEqualsCheckable()) { assertEquals("obj != deserialize(serialize(obj))", obj, dest); } } } /** * Sanity check method, makes sure that any Serializable * class can be serialized and de-serialized in memory, * using the handy makeObject() method * * @throws IOException * @throws ClassNotFoundException */ public void testSimpleSerialization() throws Exception { Object o = makeObject(); if (o instanceof Serializable && isTestSerialization()) { byte[] objekt = writeExternalFormToBytes((Serializable) o); Object p = readExternalFormFromBytes(objekt); } } /** * Tests serialization by comparing against a previously stored version in CVS. * If the test object is serializable, confirm that a canonical form exists. */ public void testCanonicalEmptyCollectionExists() { if (supportsEmptyCollections() && isTestSerialization() && !skipSerializedCanonicalTests()) { Object object = makeObject(); if (object instanceof Serializable) { String name = getCanonicalEmptyCollectionName(object); assertTrue("Canonical empty collection (" + name + ") is not in CVS", new File(name).exists()); } } } /** * Tests serialization by comparing against a previously stored version in CVS. * If the test object is serializable, confirm that a canonical form exists. */ public void testCanonicalFullCollectionExists() { if (supportsFullCollections() && isTestSerialization() && !skipSerializedCanonicalTests()) { Object object = makeObject(); if (object instanceof Serializable) { String name = getCanonicalFullCollectionName(object); assertTrue("Canonical full collection (" + name + ") is not in CVS", new File(name).exists()); } } } // protected implementation //----------------------------------------------------------------------- /** * Get the version of Collections that this object tries to * maintain serialization compatibility with. Defaults to 1, the * earliest Collections version. (Note: some collections15 did not * even exist in this version). *

                  * This constant makes it possible for TestMap (and other subclasses, * if necessary) to automatically check CVS for a versionX copy of a * Serialized object, so we can make sure that compatibility is maintained. * See, for example, TestMap.getCanonicalFullMapName(Map map). * Subclasses can override this variable, indicating compatibility * with earlier Collections versions. * * @return The version, or null if this object shouldn't be * tested for compatibility with previous versions. */ public String getCompatibilityVersion() { return "1"; } protected String getCanonicalEmptyCollectionName(Object object) { StringBuffer retval = new StringBuffer(); retval.append("data/test/"); String colName = object.getClass().getName(); colName = colName.substring(colName.lastIndexOf(".") + 1, colName.length()); retval.append(colName); retval.append(".emptyCollection.version"); retval.append(getCompatibilityVersion()); retval.append(".obj"); return retval.toString(); } protected String getCanonicalFullCollectionName(Object object) { StringBuffer retval = new StringBuffer(); retval.append("data/test/"); String colName = object.getClass().getName(); colName = colName.substring(colName.lastIndexOf(".") + 1, colName.length()); retval.append(colName); retval.append(".fullCollection.version"); retval.append(getCompatibilityVersion()); retval.append(".obj"); return retval.toString(); } /** * Write a Serializable or Externalizable object as * a file at the given path. NOT USEFUL as part * of a unit test; this is just a utility method * for creating disk-based objects in CVS that can become * the basis for compatibility tests using * readExternalFormFromDisk(String path) * * @param o Object to serialize * @param path path to write the serialized Object * @throws IOException */ protected void writeExternalFormToDisk(Serializable o, String path) throws IOException { FileOutputStream fileStream = new FileOutputStream(path); writeExternalFormToStream(o, fileStream); } /** * Converts a Serializable or Externalizable object to * bytes. Useful for in-memory tests of serialization * * @param o Object to convert to bytes * @return serialized form of the Object * @throws IOException */ protected byte[] writeExternalFormToBytes(Serializable o) throws IOException { ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); writeExternalFormToStream(o, byteStream); return byteStream.toByteArray(); } /** * Reads a Serialized or Externalized Object from disk. * Useful for creating compatibility tests between * different CVS versions of the same class * * @param path path to the serialized Object * @return the Object at the given path * @throws IOException * @throws ClassNotFoundException */ protected Object readExternalFormFromDisk(String path) throws IOException, ClassNotFoundException { FileInputStream stream = new FileInputStream(path); return readExternalFormFromStream(stream); } /** * Read a Serialized or Externalized Object from bytes. * Useful for verifying serialization in memory. * * @param b byte array containing a serialized Object * @return Object contained in the bytes * @throws IOException * @throws ClassNotFoundException */ protected Object readExternalFormFromBytes(byte[] b) throws IOException, ClassNotFoundException { ByteArrayInputStream stream = new ByteArrayInputStream(b); return readExternalFormFromStream(stream); } protected boolean skipSerializedCanonicalTests() { return Boolean.getBoolean("org.apache.commons.collections15:with-clover"); } // private implementation //----------------------------------------------------------------------- private Object readExternalFormFromStream(InputStream stream) throws IOException, ClassNotFoundException { ObjectInputStream oStream = new ObjectInputStream(stream); return oStream.readObject(); } private void writeExternalFormToStream(Serializable o, OutputStream stream) throws IOException { ObjectOutputStream oStream = new ObjectOutputStream(stream); oStream.writeObject(o); } } collections-generic-4.01/src/test/org/apache/commons/collections15/TestTransformerUtils.java0000644000175000017500000004437610464140763032562 0ustar giovannigiovanni/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15; import junit.framework.Test; import junit.framework.TestSuite; import junit.textui.TestRunner; import org.apache.commons.collections15.functors.ConstantTransformer; import org.apache.commons.collections15.functors.NOPTransformer; import java.util.*; /** * Tests the org.apache.commons.collections15.TransformerUtils class. * * @author Stephen Colebourne * @author Matt Hall, John Watkinson, James Carman * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:39 $ * @since Commons Collections 3.0 */ public class TestTransformerUtils extends junit.framework.TestCase { private static final Object cObject = new Object(); private static final Object cString = "Hello"; private static final Object cInteger = new Integer(6); /** * Construct */ public TestTransformerUtils(String name) { super(name); } /** * Main. * * @param args */ public static void main(String[] args) { TestRunner.run(suite()); } /** * Return class as a test suite. */ public static Test suite() { return new TestSuite(TestTransformerUtils.class); } /** * Set up instance variables required by this test case. */ public void setUp() { } /** * Tear down instance variables required by this test case. */ public void tearDown() { } // exceptionTransformer //------------------------------------------------------------------ public void testExceptionTransformer() { assertNotNull(TransformerUtils.exceptionTransformer()); assertSame(TransformerUtils.exceptionTransformer(), TransformerUtils.exceptionTransformer()); try { TransformerUtils.exceptionTransformer().transform(null); } catch (FunctorException ex) { try { TransformerUtils.exceptionTransformer().transform(cString); } catch (FunctorException ex2) { return; } } fail(); } // nullTransformer //------------------------------------------------------------------ public void testNullTransformer() { assertNotNull(TransformerUtils.nullTransformer()); assertSame(TransformerUtils.nullTransformer(), TransformerUtils.nullTransformer()); assertEquals(null, TransformerUtils.nullTransformer().transform(null)); assertEquals(null, TransformerUtils.nullTransformer().transform(cObject)); assertEquals(null, TransformerUtils.nullTransformer().transform(cString)); assertEquals(null, TransformerUtils.nullTransformer().transform(cInteger)); } // nopTransformer //------------------------------------------------------------------ public void testNopTransformer() { assertNotNull(TransformerUtils.nullTransformer()); assertSame(TransformerUtils.nullTransformer(), TransformerUtils.nullTransformer()); assertEquals(null, TransformerUtils.nopTransformer().transform(null)); assertEquals(cObject, TransformerUtils.nopTransformer().transform(cObject)); assertEquals(cString, TransformerUtils.nopTransformer().transform(cString)); assertEquals(cInteger, TransformerUtils.nopTransformer().transform(cInteger)); } // constantTransformer //------------------------------------------------------------------ public void testConstantTransformer() { assertEquals(cObject, TransformerUtils.constantTransformer(cObject).transform(null)); assertEquals(cObject, TransformerUtils.constantTransformer(cObject).transform(cObject)); assertEquals(cObject, TransformerUtils.constantTransformer(cObject).transform(cString)); assertEquals(cObject, TransformerUtils.constantTransformer(cObject).transform(cInteger)); assertSame(ConstantTransformer.NULL_INSTANCE, TransformerUtils.constantTransformer(null)); } // cloneTransformer //------------------------------------------------------------------ public void testCloneTransformer() { assertEquals(null, TransformerUtils.cloneTransformer().transform(null)); assertEquals(cString, TransformerUtils.cloneTransformer().transform(cString)); assertEquals(cInteger, TransformerUtils.cloneTransformer().transform(cInteger)); try { assertEquals(cObject, TransformerUtils.cloneTransformer().transform(cObject)); } catch (IllegalArgumentException ex) { return; } fail(); } // mapTransformer //------------------------------------------------------------------ public void testMapTransformer() { Map map = new HashMap(); map.put(null, new Integer(0)); map.put(cObject, new Integer(1)); map.put(cString, new Integer(2)); assertEquals(new Integer(0), TransformerUtils.mapTransformer(map).transform(null)); assertEquals(new Integer(1), TransformerUtils.mapTransformer(map).transform(cObject)); assertEquals(new Integer(2), TransformerUtils.mapTransformer(map).transform(cString)); assertEquals(null, TransformerUtils.mapTransformer(map).transform(cInteger)); assertSame(ConstantTransformer.NULL_INSTANCE, TransformerUtils.mapTransformer(null)); } // commandTransformer //------------------------------------------------------------------ public void testExecutorTransformer() { assertEquals(null, TransformerUtils.asTransformer(ClosureUtils.nopClosure()).transform(null)); assertEquals(cObject, TransformerUtils.asTransformer(ClosureUtils.nopClosure()).transform(cObject)); assertEquals(cString, TransformerUtils.asTransformer(ClosureUtils.nopClosure()).transform(cString)); assertEquals(cInteger, TransformerUtils.asTransformer(ClosureUtils.nopClosure()).transform(cInteger)); try { TransformerUtils.asTransformer((Closure) null); } catch (IllegalArgumentException ex) { return; } fail(); } // predicateTransformer //------------------------------------------------------------------ public void testPredicateTransformer() { assertEquals(Boolean.TRUE, TransformerUtils.asTransformer(PredicateUtils.truePredicate()).transform(null)); assertEquals(Boolean.TRUE, TransformerUtils.asTransformer(PredicateUtils.truePredicate()).transform(cObject)); assertEquals(Boolean.TRUE, TransformerUtils.asTransformer(PredicateUtils.truePredicate()).transform(cString)); assertEquals(Boolean.TRUE, TransformerUtils.asTransformer(PredicateUtils.truePredicate()).transform(cInteger)); try { TransformerUtils.asTransformer((Predicate) null); } catch (IllegalArgumentException ex) { return; } fail(); } // factoryTransformer //------------------------------------------------------------------ public void testFactoryTransformer() { assertEquals(null, TransformerUtils.asTransformer(FactoryUtils.nullFactory()).transform(null)); assertEquals(null, TransformerUtils.asTransformer(FactoryUtils.nullFactory()).transform(cObject)); assertEquals(null, TransformerUtils.asTransformer(FactoryUtils.nullFactory()).transform(cString)); assertEquals(null, TransformerUtils.asTransformer(FactoryUtils.nullFactory()).transform(cInteger)); try { TransformerUtils.asTransformer((Factory) null); } catch (IllegalArgumentException ex) { return; } fail(); } // chainedTransformer //------------------------------------------------------------------ public void testChainedTransformer() { Transformer a = TransformerUtils.constantTransformer("A"); Transformer b = TransformerUtils.constantTransformer("B"); assertEquals("A", TransformerUtils.chainedTransformer(b, a).transform(null)); assertEquals("B", TransformerUtils.chainedTransformer(a, b).transform(null)); assertEquals("A", TransformerUtils.chainedTransformer(new Transformer[]{b, a}).transform(null)); Collection coll = new ArrayList(); coll.add(b); coll.add(a); assertEquals("A", TransformerUtils.chainedTransformer(coll).transform(null)); assertSame(NOPTransformer.INSTANCE, TransformerUtils.chainedTransformer(new Transformer[0])); assertSame(NOPTransformer.INSTANCE, TransformerUtils.chainedTransformer(Collections.EMPTY_LIST)); try { TransformerUtils.chainedTransformer(null, null); fail(); } catch (IllegalArgumentException ex) { } try { TransformerUtils.chainedTransformer((Transformer[]) null); fail(); } catch (IllegalArgumentException ex) { } try { TransformerUtils.chainedTransformer((Collection) null); fail(); } catch (IllegalArgumentException ex) { } try { TransformerUtils.chainedTransformer(new Transformer[]{null, null}); fail(); } catch (IllegalArgumentException ex) { } try { coll = new ArrayList(); coll.add(null); coll.add(null); TransformerUtils.chainedTransformer(coll); fail(); } catch (IllegalArgumentException ex) { } } // switchTransformer //------------------------------------------------------------------ public void testSwitchTransformer() { Transformer a = TransformerUtils.constantTransformer("A"); Transformer b = TransformerUtils.constantTransformer("B"); Transformer c = TransformerUtils.constantTransformer("C"); assertEquals("A", TransformerUtils.switchTransformer(PredicateUtils.truePredicate(), a, b).transform(null)); assertEquals("B", TransformerUtils.switchTransformer(PredicateUtils.falsePredicate(), a, b).transform(null)); assertEquals(null, TransformerUtils.switchTransformer(new Predicate[]{PredicateUtils.equalPredicate("HELLO"), PredicateUtils.equalPredicate("THERE")}, new Transformer[]{a, b}).transform("WELL")); assertEquals("A", TransformerUtils.switchTransformer(new Predicate[]{PredicateUtils.equalPredicate("HELLO"), PredicateUtils.equalPredicate("THERE")}, new Transformer[]{a, b}).transform("HELLO")); assertEquals("B", TransformerUtils.switchTransformer(new Predicate[]{PredicateUtils.equalPredicate("HELLO"), PredicateUtils.equalPredicate("THERE")}, new Transformer[]{a, b}).transform("THERE")); assertEquals("C", TransformerUtils.switchTransformer(new Predicate[]{PredicateUtils.equalPredicate("HELLO"), PredicateUtils.equalPredicate("THERE")}, new Transformer[]{a, b}, c).transform("WELL")); Map map = new HashMap(); map.put(PredicateUtils.equalPredicate("HELLO"), a); map.put(PredicateUtils.equalPredicate("THERE"), b); assertEquals(null, TransformerUtils.switchTransformer(map).transform("WELL")); assertEquals("A", TransformerUtils.switchTransformer(map).transform("HELLO")); assertEquals("B", TransformerUtils.switchTransformer(map).transform("THERE")); map.put(null, c); assertEquals("C", TransformerUtils.switchTransformer(map).transform("WELL")); assertSame(ConstantTransformer.NULL_INSTANCE, TransformerUtils.switchTransformer(new Predicate[0], new Transformer[0])); assertSame(ConstantTransformer.NULL_INSTANCE, TransformerUtils.switchTransformer(new HashMap())); map = new HashMap(); map.put(null, null); assertSame(ConstantTransformer.NULL_INSTANCE, TransformerUtils.switchTransformer(map)); try { TransformerUtils.switchTransformer(null, null); fail(); } catch (IllegalArgumentException ex) { } try { TransformerUtils.switchTransformer((Predicate[]) null, (Transformer[]) null); fail(); } catch (IllegalArgumentException ex) { } try { TransformerUtils.switchTransformer((Map) null); fail(); } catch (IllegalArgumentException ex) { } try { TransformerUtils.switchTransformer(new Predicate[2], new Transformer[2]); fail(); } catch (IllegalArgumentException ex) { } try { TransformerUtils.switchTransformer(new Predicate[]{PredicateUtils.truePredicate()}, new Transformer[]{a, b}); fail(); } catch (IllegalArgumentException ex) { } } // switchMapTransformer //------------------------------------------------------------------ public void testSwitchMapTransformer() { Transformer a = TransformerUtils.constantTransformer("A"); Transformer b = TransformerUtils.constantTransformer("B"); Transformer c = TransformerUtils.constantTransformer("C"); Map map = new HashMap(); map.put("HELLO", a); map.put("THERE", b); assertEquals(null, TransformerUtils.switchMapTransformer(map).transform("WELL")); assertEquals("A", TransformerUtils.switchMapTransformer(map).transform("HELLO")); assertEquals("B", TransformerUtils.switchMapTransformer(map).transform("THERE")); map.put(null, c); assertEquals("C", TransformerUtils.switchMapTransformer(map).transform("WELL")); assertSame(ConstantTransformer.NULL_INSTANCE, TransformerUtils.switchMapTransformer(new HashMap())); map = new HashMap(); map.put(null, null); assertSame(ConstantTransformer.NULL_INSTANCE, TransformerUtils.switchMapTransformer(map)); try { TransformerUtils.switchMapTransformer(null); fail(); } catch (IllegalArgumentException ex) { } } // invokerTransformer //------------------------------------------------------------------ public void testInvokerTransformer() { List list = new ArrayList(); assertEquals(new Integer(0), TransformerUtils.invokerTransformer("size").transform(list)); list.add(new Object()); assertEquals(new Integer(1), TransformerUtils.invokerTransformer("size").transform(list)); assertEquals(null, TransformerUtils.invokerTransformer("size").transform(null)); try { TransformerUtils.invokerTransformer(null); fail(); } catch (IllegalArgumentException ex) { } try { TransformerUtils.invokerTransformer("noSuchMethod").transform(new Object()); fail(); } catch (FunctorException ex) { } } // invokerTransformer2 //------------------------------------------------------------------ public void testInvokerTransformer2() { List list = new ArrayList(); assertEquals(Boolean.FALSE, TransformerUtils.invokerTransformer("contains", new Class[]{Object.class}, new Object[]{cString}).transform(list)); list.add(cString); assertEquals(Boolean.TRUE, TransformerUtils.invokerTransformer("contains", new Class[]{Object.class}, new Object[]{cString}).transform(list)); assertEquals(null, TransformerUtils.invokerTransformer("contains", new Class[]{Object.class}, new Object[]{cString}).transform(null)); try { TransformerUtils.invokerTransformer(null, null, null); fail(); } catch (IllegalArgumentException ex) { } try { TransformerUtils.invokerTransformer("noSuchMethod", new Class[]{Object.class}, new Object[]{cString}).transform(new Object()); fail(); } catch (FunctorException ex) { } try { TransformerUtils.invokerTransformer("badArgs", null, new Object[]{cString}); fail(); } catch (IllegalArgumentException ex) { } try { TransformerUtils.invokerTransformer("badArgs", new Class[]{Object.class}, null); fail(); } catch (IllegalArgumentException ex) { } try { TransformerUtils.invokerTransformer("badArgs", new Class[]{}, new Object[]{cString}); fail(); } catch (IllegalArgumentException ex) { } } // stringValueTransformer //------------------------------------------------------------------ public void testStringValueTransformer() { assertNotNull("StringValueTransformer should NEVER return a null value.", TransformerUtils.stringValueTransformer().transform(null)); assertEquals("StringValueTransformer should return \"null\" when given a null argument.", "null", TransformerUtils.stringValueTransformer().transform(null)); assertEquals("StringValueTransformer should return toString value", "6", TransformerUtils.stringValueTransformer().transform(new Integer(6))); } // instantiateFactory //------------------------------------------------------------------ public void testInstantiateTransformerNull() { try { Transformer trans = TransformerUtils.instantiateTransformer(null, new Object[]{"str"}); fail(); } catch (IllegalArgumentException ex) { } try { Transformer trans = TransformerUtils.instantiateTransformer(new Class[]{}, new Object[]{"str"}); fail(); } catch (IllegalArgumentException ex) { } Transformer trans = TransformerUtils.instantiateTransformer(new Class[]{Long.class}, new Object[]{null}); try { trans.transform(String.class); fail(); } catch (FunctorException ex) { } trans = TransformerUtils.instantiateTransformer(); assertEquals("", trans.transform(String.class)); trans = TransformerUtils.instantiateTransformer(new Class[]{Long.TYPE}, new Object[]{new Long(1000L)}); assertEquals(new Date(1000L), trans.transform(Date.class)); } } collections-generic-4.01/src/test/org/apache/commons/collections15/TestLinkedList.java0000644000175000017500000001450410464140762031266 0ustar giovannigiovanni/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15; import org.apache.commons.collections15.list.AbstractTestList; import java.util.*; /** * Tests base {@link java.util.LinkedList} methods and contracts. *

                  * To use, simply extend this class, and implement * the {@link #makeLinkedList} method. *

                  * If your {@link LinkedList} fails one of these tests by design, * you may still use this base set of cases. Simply override the * test case (method) your {@link List} fails. * * @author Matt Hall, John Watkinson, Rich Dougherty * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:39 $ */ public abstract class TestLinkedList extends AbstractTestList { public TestLinkedList(String testName) { super(testName); } public List makeEmptyList() { return makeEmptyLinkedList(); } public List makeFullList() { return makeFullLinkedList(); } /** * Return a new, empty {@link LinkedList} to be used for testing. * * @return an empty list for testing. */ protected abstract LinkedList makeEmptyLinkedList(); /** * Return a new, full {@link List} to be used for testing. * * @return a full list for testing */ protected LinkedList makeFullLinkedList() { // only works if list supports optional "addAll(Collection)" LinkedList list = makeEmptyLinkedList(); list.addAll(Arrays.asList(getFullElements())); return list; } /** * Returns the {@link #collection} field cast to a {@link LinkedList}. * * @return the collection field as a List */ protected LinkedList getLinkedList() { return (LinkedList) collection; } /** * Returns the {@link #confirmed} field cast to a {@link LinkedList}. * * @return the confirmed field as a List */ protected LinkedList getConfirmedLinkedList() { return (LinkedList) confirmed; } /** * Tests {@link LinkedList#addFirst(Object)}. */ public void testLinkedListAddFirst() { if (!isAddSupported()) return; Object o = "hello"; resetEmpty(); getLinkedList().addFirst(o); getConfirmedLinkedList().addFirst(o); verify(); resetFull(); getLinkedList().addFirst(o); getConfirmedLinkedList().addFirst(o); verify(); } /** * Tests {@link LinkedList#addLast(Object)}. */ public void testLinkedListAddLast() { if (!isAddSupported()) return; Object o = "hello"; resetEmpty(); getLinkedList().addLast(o); getConfirmedLinkedList().addLast(o); verify(); resetFull(); getLinkedList().addLast(o); getConfirmedLinkedList().addLast(o); verify(); } /** * Tests {@link LinkedList#getFirst(Object)}. */ public void testLinkedListGetFirst() { resetEmpty(); try { getLinkedList().getFirst(); fail("getFirst() should throw a NoSuchElementException for an " + "empty list."); } catch (NoSuchElementException e) { // This is correct } verify(); resetFull(); Object first = getLinkedList().getFirst(); Object confirmedFirst = getConfirmedLinkedList().getFirst(); assertEquals("Result returned by getFirst() was wrong.", confirmedFirst, first); verify(); } /** * Tests {@link LinkedList#getLast(Object)}. */ public void testLinkedListGetLast() { resetEmpty(); try { getLinkedList().getLast(); fail("getLast() should throw a NoSuchElementException for an " + "empty list."); } catch (NoSuchElementException e) { // This is correct } verify(); resetFull(); Object last = getLinkedList().getLast(); Object confirmedLast = getConfirmedLinkedList().getLast(); assertEquals("Result returned by getLast() was wrong.", confirmedLast, last); verify(); } /** * Tests {@link LinkedList#removeFirst(Object)}. */ public void testLinkedListRemoveFirst() { if (!isRemoveSupported()) return; resetEmpty(); try { getLinkedList().removeFirst(); fail("removeFirst() should throw a NoSuchElementException for " + "an empty list."); } catch (NoSuchElementException e) { // This is correct } verify(); resetFull(); Object first = getLinkedList().removeFirst(); Object confirmedFirst = getConfirmedLinkedList().removeFirst(); assertEquals("Result returned by removeFirst() was wrong.", confirmedFirst, first); verify(); } /** * Tests {@link LinkedList#removeLast(Object)}. */ public void testLinkedListRemoveLast() { if (!isRemoveSupported()) return; resetEmpty(); try { getLinkedList().removeLast(); fail("removeLast() should throw a NoSuchElementException for " + "an empty list."); } catch (NoSuchElementException e) { // This is correct } verify(); resetFull(); Object last = getLinkedList().removeLast(); Object confirmedLast = getConfirmedLinkedList().removeLast(); assertEquals("Result returned by removeLast() was wrong.", confirmedLast, last); verify(); } /** * Returns an empty {@link ArrayList}. */ public Collection makeConfirmedCollection() { return new LinkedList(); } /** * Returns a full {@link ArrayList}. */ public Collection makeConfirmedFullCollection() { List list = new LinkedList(); list.addAll(Arrays.asList(getFullElements())); return list; } } collections-generic-4.01/src/test/org/apache/commons/collections15/keyvalue/0000755000175000017500000000000011664401370027340 5ustar giovannigiovannicollections-generic-4.01/src/test/org/apache/commons/collections15/keyvalue/TestTiedMapEntry.java0000644000175000017500000000537410464140760033421 0ustar giovannigiovanni/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.keyvalue; import junit.framework.Test; import junit.framework.TestSuite; import java.util.HashMap; import java.util.Map; /** * Test the TiedMapEntry class. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 19:11:58 $ * @since Commons Collections 3.0 */ public class TestTiedMapEntry extends AbstractTestMapEntry { public TestTiedMapEntry(String testName) { super(testName); } public static void main(String[] args) { junit.textui.TestRunner.run(TestTiedMapEntry.class); } public static Test suite() { return new TestSuite(TestTiedMapEntry.class); } //----------------------------------------------------------------------- /** * Gets the instance to test */ public Map.Entry makeMapEntry(Object key, Object value) { Map map = new HashMap(); map.put(key, value); return new TiedMapEntry(map, key); } //----------------------------------------------------------------------- /** * Tests the constructors. */ public void testConstructors() { // ignore } /** * Tests the constructors. */ public void testSetValue() { Map map = new HashMap(); map.put("A", "a"); map.put("B", "b"); map.put("C", "c"); Map.Entry entry = new TiedMapEntry(map, "A"); assertSame("A", entry.getKey()); assertSame("a", entry.getValue()); assertSame("a", entry.setValue("x")); assertSame("A", entry.getKey()); assertSame("x", entry.getValue()); entry = new TiedMapEntry(map, "B"); assertSame("B", entry.getKey()); assertSame("b", entry.getValue()); assertSame("b", entry.setValue("y")); assertSame("B", entry.getKey()); assertSame("y", entry.getValue()); entry = new TiedMapEntry(map, "C"); assertSame("C", entry.getKey()); assertSame("c", entry.getValue()); assertSame("c", entry.setValue("z")); assertSame("C", entry.getKey()); assertSame("z", entry.getValue()); } } collections-generic-4.01/src/test/org/apache/commons/collections15/keyvalue/TestMultiKey.java0000644000175000017500000001712710464140755032622 0ustar giovannigiovanni/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.keyvalue; import junit.framework.Assert; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import java.util.Arrays; /** * Unit tests for {@link org.apache.commons.collections15.MultiKey}. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 19:11:58 $ */ public class TestMultiKey extends TestCase { Integer ONE = new Integer(1); Integer TWO = new Integer(2); Integer THREE = new Integer(3); Integer FOUR = new Integer(4); Integer FIVE = new Integer(5); public TestMultiKey(String name) { super(name); } public static Test suite() { return new TestSuite(TestMultiKey.class); } public static void main(String[] args) { String[] testCaseName = {TestMultiKey.class.getName()}; junit.textui.TestRunner.main(testCaseName); } public void setUp() throws Exception { super.setUp(); } protected void tearDown() throws Exception { super.tearDown(); } //----------------------------------------------------------------------- public void testConstructors() throws Exception { MultiKey mk = null; mk = new MultiKey(ONE, TWO); Assert.assertTrue(Arrays.equals(new Object[]{ONE, TWO}, mk.getKeys())); mk = new MultiKey(ONE, TWO, THREE); Assert.assertTrue(Arrays.equals(new Object[]{ONE, TWO, THREE}, mk.getKeys())); mk = new MultiKey(ONE, TWO, THREE, FOUR); Assert.assertTrue(Arrays.equals(new Object[]{ONE, TWO, THREE, FOUR}, mk.getKeys())); mk = new MultiKey(ONE, TWO, THREE, FOUR, FIVE); Assert.assertTrue(Arrays.equals(new Object[]{ONE, TWO, THREE, FOUR, FIVE}, mk.getKeys())); mk = new MultiKey(new Object[]{THREE, FOUR, ONE, TWO}, false); Assert.assertTrue(Arrays.equals(new Object[]{THREE, FOUR, ONE, TWO}, mk.getKeys())); } public void testConstructorsByArray() throws Exception { MultiKey mk = null; Object[] keys = new Object[]{THREE, FOUR, ONE, TWO}; mk = new MultiKey(keys); Assert.assertTrue(Arrays.equals(new Object[]{THREE, FOUR, ONE, TWO}, mk.getKeys())); keys[3] = FIVE; // no effect Assert.assertTrue(Arrays.equals(new Object[]{THREE, FOUR, ONE, TWO}, mk.getKeys())); keys = new Object[]{}; mk = new MultiKey(keys); Assert.assertTrue(Arrays.equals(new Object[]{}, mk.getKeys())); keys = new Object[]{THREE, FOUR, ONE, TWO}; mk = new MultiKey(keys, true); Assert.assertTrue(Arrays.equals(new Object[]{THREE, FOUR, ONE, TWO}, mk.getKeys())); keys[3] = FIVE; // no effect Assert.assertTrue(Arrays.equals(new Object[]{THREE, FOUR, ONE, TWO}, mk.getKeys())); keys = new Object[]{THREE, FOUR, ONE, TWO}; mk = new MultiKey(keys, false); Assert.assertTrue(Arrays.equals(new Object[]{THREE, FOUR, ONE, TWO}, mk.getKeys())); // change key - don't do this! // the hashcode of the MultiKey is now broken keys[3] = FIVE; Assert.assertTrue(Arrays.equals(new Object[]{THREE, FOUR, ONE, FIVE}, mk.getKeys())); } public void testConstructorsByArrayNull() throws Exception { Object[] keys = null; try { new MultiKey(keys); fail(); } catch (IllegalArgumentException ex) { } try { new MultiKey(keys, true); fail(); } catch (IllegalArgumentException ex) { } try { new MultiKey(keys, false); fail(); } catch (IllegalArgumentException ex) { } } public void testSize() { Assert.assertEquals(2, new MultiKey(ONE, TWO).size()); Assert.assertEquals(2, new MultiKey(null, null).size()); Assert.assertEquals(3, new MultiKey(ONE, TWO, THREE).size()); Assert.assertEquals(3, new MultiKey(null, null, null).size()); Assert.assertEquals(4, new MultiKey(ONE, TWO, THREE, FOUR).size()); Assert.assertEquals(4, new MultiKey(null, null, null, null).size()); Assert.assertEquals(5, new MultiKey(ONE, TWO, THREE, FOUR, FIVE).size()); Assert.assertEquals(5, new MultiKey(null, null, null, null, null).size()); Assert.assertEquals(0, new MultiKey(new Object[]{}).size()); Assert.assertEquals(1, new MultiKey(new Object[]{ONE}).size()); Assert.assertEquals(2, new MultiKey(new Object[]{ONE, TWO}).size()); Assert.assertEquals(7, new MultiKey(new Object[]{ONE, TWO, ONE, TWO, ONE, TWO, ONE}).size()); } public void testGetIndexed() { MultiKey mk = new MultiKey(ONE, TWO); Assert.assertSame(ONE, mk.getKey(0)); Assert.assertSame(TWO, mk.getKey(1)); try { mk.getKey(-1); fail(); } catch (IndexOutOfBoundsException ex) { } try { mk.getKey(2); fail(); } catch (IndexOutOfBoundsException ex) { } } public void testGetKeysSimpleConstructor() { MultiKey mk = new MultiKey(ONE, TWO); Object[] array = mk.getKeys(); Assert.assertSame(ONE, array[0]); Assert.assertSame(TWO, array[1]); Assert.assertEquals(2, array.length); } public void testGetKeysArrayConstructorCloned() { Object[] keys = new Object[]{ONE, TWO}; MultiKey mk = new MultiKey(keys, true); Object[] array = mk.getKeys(); Assert.assertTrue(array != keys); Assert.assertTrue(Arrays.equals(array, keys)); Assert.assertSame(ONE, array[0]); Assert.assertSame(TWO, array[1]); Assert.assertEquals(2, array.length); } public void testGetKeysArrayConstructorNonCloned() { Object[] keys = new Object[]{ONE, TWO}; MultiKey mk = new MultiKey(keys, false); Object[] array = mk.getKeys(); Assert.assertTrue(array != keys); // still not equal Assert.assertTrue(Arrays.equals(array, keys)); Assert.assertSame(ONE, array[0]); Assert.assertSame(TWO, array[1]); Assert.assertEquals(2, array.length); } public void testHashCode() { MultiKey mk1 = new MultiKey(ONE, TWO); MultiKey mk2 = new MultiKey(ONE, TWO); MultiKey mk3 = new MultiKey(ONE, "TWO"); Assert.assertTrue(mk1.hashCode() == mk1.hashCode()); Assert.assertTrue(mk1.hashCode() == mk2.hashCode()); Assert.assertTrue(mk1.hashCode() != mk3.hashCode()); int total = (0 ^ ONE.hashCode()) ^ TWO.hashCode(); Assert.assertEquals(total, mk1.hashCode()); } public void testEquals() { MultiKey mk1 = new MultiKey(ONE, TWO); MultiKey mk2 = new MultiKey(ONE, TWO); MultiKey mk3 = new MultiKey(ONE, "TWO"); Assert.assertEquals(mk1, mk1); Assert.assertEquals(mk1, mk2); Assert.assertTrue(mk1.equals(mk3) == false); Assert.assertTrue(mk1.equals("") == false); Assert.assertTrue(mk1.equals(null) == false); } } collections-generic-4.01/src/test/org/apache/commons/collections15/keyvalue/TestDefaultMapEntry.java0000644000175000017500000000621510464140760034113 0ustar giovannigiovanni/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.keyvalue; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.collections15.KeyValue; import java.util.Map; /** * Test the DefaultMapEntry class. * * @author Matt Hall, John Watkinson, Neil O'Toole * @version $Revision: 1.1 $ $Date: 2005/10/11 19:11:58 $ * @since Commons Collections 3.0 */ public class TestDefaultMapEntry extends AbstractTestMapEntry { public TestDefaultMapEntry(String testName) { super(testName); } public static void main(String[] args) { junit.textui.TestRunner.run(TestDefaultMapEntry.class); } public static Test suite() { return new TestSuite(TestDefaultMapEntry.class); } //----------------------------------------------------------------------- /** * Make an instance of Map.Entry with the default (null) key and value. * Subclasses should override this method to return a Map.Entry * of the type being tested. */ public Map.Entry makeMapEntry() { return new DefaultMapEntry(null, null); } /** * Make an instance of Map.Entry with the specified key and value. * Subclasses should override this method to return a Map.Entry * of the type being tested. */ public Map.Entry makeMapEntry(Object key, Object value) { return new DefaultMapEntry(key, value); } //----------------------------------------------------------------------- /** * Subclasses should override this method. */ public void testConstructors() { // 1. test key-value constructor Map.Entry entry = new DefaultMapEntry(key, value); assertSame(key, entry.getKey()); assertSame(value, entry.getValue()); // 2. test pair constructor KeyValue pair = new DefaultKeyValue(key, value); assertSame(key, pair.getKey()); assertSame(value, pair.getValue()); // 3. test copy constructor Map.Entry entry2 = new DefaultMapEntry(entry); assertSame(key, entry2.getKey()); assertSame(value, entry2.getValue()); // test that the objects are independent entry.setValue(null); assertSame(value, entry2.getValue()); } public void testSelfReferenceHandling() { Map.Entry entry = makeMapEntry(); try { entry.setValue(entry); assertSame(entry, entry.getValue()); } catch (Exception e) { fail("This Map.Entry implementation supports value self-reference."); } } } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootcollections-generic-4.01/src/test/org/apache/commons/collections15/keyvalue/AbstractTestMapEntry.javacollections-generic-4.01/src/test/org/apache/commons/collections15/keyvalue/AbstractTestMapEntry.jav0000644000175000017500000001171610464140761034134 0ustar giovannigiovanni/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.keyvalue; import junit.framework.TestCase; import java.util.HashMap; import java.util.Map; /** * Abstract tests that can be extended to test any Map.Entry implementation. * Subclasses must implement {@link #makeMapEntry(Object, Object)} to return * a new Map.Entry of the type being tested. Subclasses must also implement * {@link #testConstructors()} to test the constructors of the Map.Entry * type being tested. * * @author Matt Hall, John Watkinson, Neil O'Toole * @version $Revision: 1.1 $ $Date: 2005/10/11 19:11:58 $ * @since Commons Collections 3.0 */ public abstract class AbstractTestMapEntry extends TestCase { protected final String key = "name"; protected final String value = "duke"; /** * JUnit constructor. * * @param testName the test name */ public AbstractTestMapEntry(String testName) { super(testName); } //----------------------------------------------------------------------- /** * Make an instance of Map.Entry with the default (null) key and value. * This implementation simply calls {@link #makeMapEntry(Object, Object)} * with null for key and value. Subclasses can override this method if desired. */ public Map.Entry makeMapEntry() { return makeMapEntry(null, null); } /** * Make an instance of Map.Entry with the specified key and value. * Subclasses should override this method to return a Map.Entry * of the type being tested. */ public abstract Map.Entry makeMapEntry(Object key, Object value); /** * Makes a Map.Entry of a type that's known to work correctly. */ public Map.Entry makeKnownMapEntry() { return makeKnownMapEntry(null, null); } /** * Makes a Map.Entry of a type that's known to work correctly. */ public Map.Entry makeKnownMapEntry(Object key, Object value) { Map map = new HashMap(1); map.put(key, value); Map.Entry entry = (Map.Entry) map.entrySet().iterator().next(); return entry; } //----------------------------------------------------------------------- public void testAccessorsAndMutators() { Map.Entry entry = makeMapEntry(key, value); assertTrue(entry.getKey() == key); entry.setValue(value); assertTrue(entry.getValue() == value); // check that null doesn't do anything funny entry = makeMapEntry(null, null); assertTrue(entry.getKey() == null); entry.setValue(null); assertTrue(entry.getValue() == null); } /** * Subclasses should override this method to test the * desired behaviour of the class with respect to * handling of self-references. */ public void testSelfReferenceHandling() { // test that #setValue does not permit // the MapEntry to contain itself (and thus cause infinite recursion // in #hashCode and #toString) Map.Entry entry = makeMapEntry(); try { entry.setValue(entry); fail("Should throw an IllegalArgumentException"); } catch (IllegalArgumentException iae) { // expected to happen... // check that the KVP's state has not changed assertTrue(entry.getKey() == null && entry.getValue() == null); } } /** * Subclasses should provide tests for their constructors. */ public abstract void testConstructors(); public void testEqualsAndHashCode() { // 1. test with object data Map.Entry e1 = makeMapEntry(key, value); Map.Entry e2 = makeKnownMapEntry(key, value); assertTrue(e1.equals(e1)); assertTrue(e2.equals(e1)); assertTrue(e1.equals(e2)); assertTrue(e1.hashCode() == e2.hashCode()); // 2. test with nulls e1 = makeMapEntry(); e2 = makeKnownMapEntry(); assertTrue(e1.equals(e1)); assertTrue(e2.equals(e1)); assertTrue(e1.equals(e2)); assertTrue(e1.hashCode() == e2.hashCode()); } public void testToString() { Map.Entry entry = makeMapEntry(key, value); assertTrue(entry.toString().equals(entry.getKey() + "=" + entry.getValue())); // test with nulls entry = makeMapEntry(); assertTrue(entry.toString().equals(entry.getKey() + "=" + entry.getValue())); } } collections-generic-4.01/src/test/org/apache/commons/collections15/keyvalue/TestAll.java0000644000175000017500000000315010464140755031556 0ustar giovannigiovanni/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.keyvalue; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * Entry point for key-value test cases. * * @author Neil O'Toole * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 19:11:58 $ * @since Commons Collections 3.0 */ public class TestAll extends TestCase { public TestAll(String testName) { super(testName); } public static void main(String args[]) { String[] testCaseName = {TestAll.class.getName()}; junit.textui.TestRunner.main(testCaseName); } public static Test suite() { TestSuite suite = new TestSuite(); suite.addTest(TestDefaultKeyValue.suite()); suite.addTest(TestDefaultMapEntry.suite()); suite.addTest(TestMultiKey.suite()); suite.addTest(TestTiedMapEntry.suite()); suite.addTest(TestUnmodifiableMapEntry.suite()); return suite; } } ././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootcollections-generic-4.01/src/test/org/apache/commons/collections15/keyvalue/TestUnmodifiableMapEntry.javacollections-generic-4.01/src/test/org/apache/commons/collections15/keyvalue/TestUnmodifiableMapEntry0000644000175000017500000000705610464140755034215 0ustar giovannigiovanni/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.keyvalue; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.collections15.KeyValue; import org.apache.commons.collections15.Unmodifiable; import java.util.Map; /** * Test the UnmodifiableMapEntry class. * * @author Matt Hall, John Watkinson, Neil O'Toole * @version $Revision: 1.1 $ $Date: 2005/10/11 19:11:58 $ * @since Commons Collections 3.0 */ public class TestUnmodifiableMapEntry extends AbstractTestMapEntry { public TestUnmodifiableMapEntry(String testName) { super(testName); } public static void main(String[] args) { junit.textui.TestRunner.run(TestUnmodifiableMapEntry.class); } public static Test suite() { return new TestSuite(TestUnmodifiableMapEntry.class); } //----------------------------------------------------------------------- /** * Make an instance of Map.Entry with the default (null) key and value. * Subclasses should override this method to return a Map.Entry * of the type being tested. */ public Map.Entry makeMapEntry() { return new UnmodifiableMapEntry(null, null); } /** * Make an instance of Map.Entry with the specified key and value. * Subclasses should override this method to return a Map.Entry * of the type being tested. */ public Map.Entry makeMapEntry(Object key, Object value) { return new UnmodifiableMapEntry(key, value); } //----------------------------------------------------------------------- /** * Subclasses should override this method. */ public void testConstructors() { // 1. test key-value constructor Map.Entry entry = new UnmodifiableMapEntry(key, value); assertSame(key, entry.getKey()); assertSame(value, entry.getValue()); // 2. test pair constructor KeyValue pair = new DefaultKeyValue(key, value); entry = new UnmodifiableMapEntry(pair); assertSame(key, entry.getKey()); assertSame(value, entry.getValue()); // 3. test copy constructor Map.Entry entry2 = new UnmodifiableMapEntry(entry); assertSame(key, entry2.getKey()); assertSame(value, entry2.getValue()); assertTrue(entry instanceof Unmodifiable); } public void testAccessorsAndMutators() { Map.Entry entry = makeMapEntry(key, value); assertSame(key, entry.getKey()); assertSame(value, entry.getValue()); // check that null doesn't do anything funny entry = makeMapEntry(null, null); assertSame(null, entry.getKey()); assertSame(null, entry.getValue()); } public void testSelfReferenceHandling() { // block } public void testUnmodifiable() { Map.Entry entry = makeMapEntry(); try { entry.setValue(null); fail(); } catch (UnsupportedOperationException ex) { } } } collections-generic-4.01/src/test/org/apache/commons/collections15/keyvalue/TestDefaultKeyValue.java0000644000175000017500000001404510464140757034107 0ustar giovannigiovanni/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.keyvalue; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import java.util.HashMap; import java.util.Map; /** * Test the DefaultKeyValue class. * * @author Matt Hall, John Watkinson, Neil O'Toole * @version $Revision: 1.1 $ $Date: 2005/10/11 19:11:58 $ * @since Commons Collections 3.0 */ public class TestDefaultKeyValue extends TestCase { private final String key = "name"; private final String value = "duke"; /** * JUnit constructor. * * @param testName the test name */ public TestDefaultKeyValue(String testName) { super(testName); } public static void main(String[] args) { junit.textui.TestRunner.run(TestDefaultKeyValue.class); } public static Test suite() { return new TestSuite(TestDefaultKeyValue.class); } //----------------------------------------------------------------------- /** * Make an instance of DefaultKeyValue with the default (null) key and value. * Subclasses should override this method to return a DefaultKeyValue * of the type being tested. */ protected DefaultKeyValue makeDefaultKeyValue() { return new DefaultKeyValue(null, null); } /** * Make an instance of DefaultKeyValue with the specified key and value. * Subclasses should override this method to return a DefaultKeyValue * of the type being tested. */ protected DefaultKeyValue makeDefaultKeyValue(Object key, Object value) { return new DefaultKeyValue(key, value); } //----------------------------------------------------------------------- public void testAccessorsAndMutators() { DefaultKeyValue kv = makeDefaultKeyValue(); kv.setKey(key); assertTrue(kv.getKey() == key); kv.setValue(value); assertTrue(kv.getValue() == value); // check that null doesn't do anything funny kv.setKey(null); assertTrue(kv.getKey() == null); kv.setValue(null); assertTrue(kv.getValue() == null); } public void testSelfReferenceHandling() { // test that #setKey and #setValue do not permit // the KVP to contain itself (and thus cause infinite recursion // in #hashCode and #toString) DefaultKeyValue kv = makeDefaultKeyValue(); try { kv.setKey(kv); fail("Should throw an IllegalArgumentException"); } catch (IllegalArgumentException iae) { // expected to happen... // check that the KVP's state has not changed assertTrue(kv.getKey() == null && kv.getValue() == null); } try { kv.setValue(kv); fail("Should throw an IllegalArgumentException"); } catch (IllegalArgumentException iae) { // expected to happen... // check that the KVP's state has not changed assertTrue(kv.getKey() == null && kv.getValue() == null); } } /** * Subclasses should override this method to test their own constructors. */ public void testConstructors() { // 1. test default constructor DefaultKeyValue kv = new DefaultKeyValue(); assertTrue(kv.getKey() == null && kv.getValue() == null); // 2. test key-value constructor kv = new DefaultKeyValue(key, value); assertTrue(kv.getKey() == key && kv.getValue() == value); // 3. test copy constructor DefaultKeyValue kv2 = new DefaultKeyValue(kv); assertTrue(kv2.getKey() == key && kv2.getValue() == value); // test that the KVPs are independent kv.setKey(null); kv.setValue(null); assertTrue(kv2.getKey() == key && kv2.getValue() == value); // 4. test Map.Entry constructor Map map = new HashMap(); map.put(key, value); Map.Entry entry = (Map.Entry) map.entrySet().iterator().next(); kv = new DefaultKeyValue(entry); assertTrue(kv.getKey() == key && kv.getValue() == value); // test that the KVP is independent of the Map.Entry entry.setValue(null); assertTrue(kv.getValue() == value); } public void testEqualsAndHashCode() { // 1. test with object data DefaultKeyValue kv = makeDefaultKeyValue(key, value); DefaultKeyValue kv2 = makeDefaultKeyValue(key, value); assertTrue(kv.equals(kv)); assertTrue(kv.equals(kv2)); assertTrue(kv.hashCode() == kv2.hashCode()); // 2. test with nulls kv = makeDefaultKeyValue(null, null); kv2 = makeDefaultKeyValue(null, null); assertTrue(kv.equals(kv)); assertTrue(kv.equals(kv2)); assertTrue(kv.hashCode() == kv2.hashCode()); } public void testToString() { DefaultKeyValue kv = makeDefaultKeyValue(key, value); assertTrue(kv.toString().equals(kv.getKey() + "=" + kv.getValue())); // test with nulls kv = makeDefaultKeyValue(null, null); assertTrue(kv.toString().equals(kv.getKey() + "=" + kv.getValue())); } public void testToMapEntry() { DefaultKeyValue kv = makeDefaultKeyValue(key, value); Map map = new HashMap(); map.put(kv.getKey(), kv.getValue()); Map.Entry entry = (Map.Entry) map.entrySet().iterator().next(); assertTrue(entry.equals(kv.toMapEntry())); assertTrue(entry.hashCode() == kv.hashCode()); } } collections-generic-4.01/src/test/org/apache/commons/collections15/TestSetUtils.java0000644000175000017500000000635610464140754031007 0ustar giovannigiovanni/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15; import junit.framework.Test; import org.apache.commons.collections15.set.PredicatedSet; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.Set; /** * Tests for SetUtils. * * @author Stephen Colebourne * @author Neil O'Toole * @author Matt Hall, John Watkinson, Matthew Hawthorne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:39 $ */ public class TestSetUtils extends BulkTest { public TestSetUtils(String name) { super(name); } public static Test suite() { return BulkTest.makeSuite(TestSetUtils.class); } public void testNothing() { } public void testpredicatedSet() { Predicate predicate = new Predicate() { public boolean evaluate(Object o) { return o instanceof String; } }; Set set = SetUtils.predicatedSet(new HashSet(), predicate); assertTrue("returned object should be a PredicatedSet", set instanceof PredicatedSet); try { set = SetUtils.predicatedSet(new HashSet(), null); fail("Expecting IllegalArgumentException for null predicate."); } catch (IllegalArgumentException ex) { // expected } try { set = SetUtils.predicatedSet(null, predicate); fail("Expecting IllegalArgumentException for null set."); } catch (IllegalArgumentException ex) { // expected } } public void testEquals() { Collection data = Arrays.asList(new String[]{"a", "b", "c"}); Set a = new HashSet(data); Set b = new HashSet(data); assertEquals(true, a.equals(b)); assertEquals(true, SetUtils.isEqualSet(a, b)); a.clear(); assertEquals(false, SetUtils.isEqualSet(a, b)); assertEquals(false, SetUtils.isEqualSet(a, null)); assertEquals(false, SetUtils.isEqualSet(null, b)); assertEquals(true, SetUtils.isEqualSet(null, null)); } public void testHashCode() { Collection data = Arrays.asList(new String[]{"a", "b", "c"}); Set a = new HashSet(data); Set b = new HashSet(data); assertEquals(true, a.hashCode() == b.hashCode()); assertEquals(true, a.hashCode() == SetUtils.hashCodeForSet(a)); assertEquals(true, b.hashCode() == SetUtils.hashCodeForSet(b)); assertEquals(true, SetUtils.hashCodeForSet(a) == SetUtils.hashCodeForSet(b)); a.clear(); assertEquals(false, SetUtils.hashCodeForSet(a) == SetUtils.hashCodeForSet(b)); assertEquals(0, SetUtils.hashCodeForSet(null)); } } collections-generic-4.01/src/test/org/apache/commons/collections15/bidimap/0000755000175000017500000000000011664401370027120 5ustar giovannigiovanni././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootcollections-generic-4.01/src/test/org/apache/commons/collections15/bidimap/AbstractTestSortedBidiMap.javacollections-generic-4.01/src/test/org/apache/commons/collections15/bidimap/AbstractTestSortedBidiMap0000644000175000017500000006466110464140756034077 0ustar giovannigiovanni/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.bidimap; import org.apache.commons.collections15.BulkTest; import org.apache.commons.collections15.SortedBidiMap; import org.apache.commons.collections15.map.AbstractTestSortedMap; import java.util.*; /** * Abstract test class for {@link SortedBidiMap} methods and contracts. * * @author Matthew Hawthorne * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:44 $ */ public abstract class AbstractTestSortedBidiMap extends AbstractTestOrderedBidiMap { protected List sortedKeys = new ArrayList(); protected List sortedValues = new ArrayList(); protected SortedSet sortedNewValues = new TreeSet(); public AbstractTestSortedBidiMap(String testName) { super(testName); sortedKeys.addAll(Arrays.asList(getSampleKeys())); Collections.sort(sortedKeys); sortedKeys = Collections.unmodifiableList(sortedKeys); Map map = new TreeMap(); for (int i = 0; i < getSampleKeys().length; i++) { map.put(getSampleKeys()[i], getSampleValues()[i]); } sortedValues.addAll(map.values()); sortedValues = Collections.unmodifiableList(sortedValues); sortedNewValues.addAll(Arrays.asList(getNewSampleValues())); } public AbstractTestSortedBidiMap() { super(); sortedKeys.addAll(Arrays.asList(getSampleValues())); Collections.sort(sortedKeys); sortedKeys = Collections.unmodifiableList(sortedKeys); Map map = new TreeMap(); for (int i = 0; i < getSampleKeys().length; i++) { map.put(getSampleValues()[i], getSampleKeys()[i]); } sortedValues.addAll(map.values()); sortedValues = Collections.unmodifiableList(sortedValues); sortedNewValues.addAll(Arrays.asList(getNewSampleValues())); } //----------------------------------------------------------------------- public boolean isAllowNullKey() { return false; } public boolean isAllowNullValue() { return false; } public Map makeConfirmedMap() { return new TreeMap(); } //----------------------------------------------------------------------- //----------------------------------------------------------------------- public void testBidiHeadMapContains() { // extra test as other tests get complex SortedBidiMap sm = (SortedBidiMap) makeFullMap(); Iterator it = sm.keySet().iterator(); Object first = it.next(); Object toKey = it.next(); Object second = it.next(); Object firstValue = sm.get(first); Object secondValue = sm.get(second); SortedMap head = sm.headMap(toKey); assertEquals(1, head.size()); assertEquals(true, sm.containsKey(first)); assertEquals(true, head.containsKey(first)); assertEquals(true, sm.containsValue(firstValue)); assertEquals(true, head.containsValue(firstValue)); assertEquals(true, sm.containsKey(second)); assertEquals(false, head.containsKey(second)); assertEquals(true, sm.containsValue(secondValue)); assertEquals(false, head.containsValue(secondValue)); } //----------------------------------------------------------------------- public void testBidiClearByHeadMap() { if (isRemoveSupported() == false) return; // extra test as other tests get complex SortedBidiMap sm = (SortedBidiMap) makeFullMap(); Iterator it = sm.keySet().iterator(); Object first = it.next(); Object second = it.next(); Object toKey = it.next(); Object firstValue = sm.get(first); Object secondValue = sm.get(second); Object toKeyValue = sm.get(toKey); SortedMap sub = sm.headMap(toKey); int size = sm.size(); assertEquals(2, sub.size()); sub.clear(); assertEquals(0, sub.size()); assertEquals(size - 2, sm.size()); assertEquals(size - 2, sm.inverseBidiMap().size()); assertEquals(false, sm.containsKey(first)); assertEquals(false, sm.containsValue(firstValue)); assertEquals(false, sm.inverseBidiMap().containsKey(firstValue)); assertEquals(false, sm.inverseBidiMap().containsValue(first)); assertEquals(false, sub.containsKey(first)); assertEquals(false, sub.containsValue(firstValue)); assertEquals(false, sm.containsKey(second)); assertEquals(false, sm.containsValue(secondValue)); assertEquals(false, sm.inverseBidiMap().containsKey(secondValue)); assertEquals(false, sm.inverseBidiMap().containsValue(second)); assertEquals(false, sub.containsKey(second)); assertEquals(false, sub.containsValue(secondValue)); assertEquals(true, sm.containsKey(toKey)); assertEquals(true, sm.containsValue(toKeyValue)); assertEquals(true, sm.inverseBidiMap().containsKey(toKeyValue)); assertEquals(true, sm.inverseBidiMap().containsValue(toKey)); assertEquals(false, sub.containsKey(toKey)); assertEquals(false, sub.containsValue(toKeyValue)); } //----------------------------------------------------------------------- public void testBidiRemoveByHeadMap() { if (isRemoveSupported() == false) return; // extra test as other tests get complex SortedBidiMap sm = (SortedBidiMap) makeFullMap(); Iterator it = sm.keySet().iterator(); Object first = it.next(); Object second = it.next(); Object toKey = it.next(); int size = sm.size(); SortedMap sub = sm.headMap(toKey); assertEquals(2, sub.size()); assertEquals(true, sm.containsKey(first)); assertEquals(true, sub.containsKey(first)); assertEquals(true, sm.containsKey(second)); assertEquals(true, sub.containsKey(second)); Object firstValue = sub.remove(first); assertEquals(1, sub.size()); assertEquals(size - 1, sm.size()); assertEquals(size - 1, sm.inverseBidiMap().size()); assertEquals(false, sm.containsKey(first)); assertEquals(false, sm.containsValue(firstValue)); assertEquals(false, sm.inverseBidiMap().containsKey(firstValue)); assertEquals(false, sm.inverseBidiMap().containsValue(first)); assertEquals(false, sub.containsKey(first)); assertEquals(false, sub.containsValue(firstValue)); Object secondValue = sub.remove(second); assertEquals(0, sub.size()); assertEquals(size - 2, sm.size()); assertEquals(size - 2, sm.inverseBidiMap().size()); assertEquals(false, sm.containsKey(second)); assertEquals(false, sm.containsValue(secondValue)); assertEquals(false, sm.inverseBidiMap().containsKey(secondValue)); assertEquals(false, sm.inverseBidiMap().containsValue(second)); assertEquals(false, sub.containsKey(second)); assertEquals(false, sub.containsValue(secondValue)); } //----------------------------------------------------------------------- public void testBidiRemoveByHeadMapEntrySet() { if (isRemoveSupported() == false) return; // extra test as other tests get complex SortedBidiMap sm = (SortedBidiMap) makeFullMap(); Iterator it = sm.keySet().iterator(); Object first = it.next(); Object second = it.next(); Object toKey = it.next(); int size = sm.size(); SortedMap sub = sm.headMap(toKey); Set set = sub.entrySet(); assertEquals(2, sub.size()); assertEquals(2, set.size()); Iterator it2 = set.iterator(); Map.Entry firstEntry = cloneMapEntry((Map.Entry) it2.next()); Map.Entry secondEntry = cloneMapEntry((Map.Entry) it2.next()); assertEquals(true, sm.containsKey(first)); assertEquals(true, sub.containsKey(first)); assertEquals(true, set.contains(firstEntry)); assertEquals(true, sm.containsKey(second)); assertEquals(true, sub.containsKey(second)); assertEquals(true, set.contains(secondEntry)); set.remove(firstEntry); assertEquals(1, sub.size()); assertEquals(size - 1, sm.size()); assertEquals(size - 1, sm.inverseBidiMap().size()); assertEquals(false, sm.containsKey(firstEntry.getKey())); assertEquals(false, sm.containsValue(firstEntry.getValue())); assertEquals(false, sm.inverseBidiMap().containsKey(firstEntry.getValue())); assertEquals(false, sm.inverseBidiMap().containsValue(firstEntry.getKey())); assertEquals(false, sub.containsKey(firstEntry.getKey())); assertEquals(false, sub.containsValue(firstEntry.getValue())); assertEquals(false, set.contains(firstEntry)); set.remove(secondEntry); assertEquals(0, sub.size()); assertEquals(size - 2, sm.size()); assertEquals(size - 2, sm.inverseBidiMap().size()); assertEquals(false, sm.containsKey(secondEntry.getKey())); assertEquals(false, sm.containsValue(secondEntry.getValue())); assertEquals(false, sm.inverseBidiMap().containsKey(secondEntry.getValue())); assertEquals(false, sm.inverseBidiMap().containsValue(secondEntry.getKey())); assertEquals(false, sub.containsKey(secondEntry.getKey())); assertEquals(false, sub.containsValue(secondEntry.getValue())); assertEquals(false, set.contains(secondEntry)); } //----------------------------------------------------------------------- //----------------------------------------------------------------------- public void testBidiTailMapContains() { // extra test as other tests get complex SortedBidiMap sm = (SortedBidiMap) makeFullMap(); Iterator it = sm.keySet().iterator(); Object first = it.next(); Object fromKey = it.next(); Object second = it.next(); Object firstValue = sm.get(first); Object fromKeyValue = sm.get(fromKey); Object secondValue = sm.get(second); SortedMap sub = sm.tailMap(fromKey); assertEquals(sm.size() - 1, sub.size()); assertEquals(true, sm.containsKey(first)); assertEquals(false, sub.containsKey(first)); assertEquals(true, sm.containsValue(firstValue)); assertEquals(false, sub.containsValue(firstValue)); assertEquals(true, sm.containsKey(fromKey)); assertEquals(true, sub.containsKey(fromKey)); assertEquals(true, sm.containsValue(fromKeyValue)); assertEquals(true, sub.containsValue(fromKeyValue)); assertEquals(true, sm.containsKey(second)); assertEquals(true, sub.containsKey(second)); assertEquals(true, sm.containsValue(secondValue)); assertEquals(true, sub.containsValue(secondValue)); } //----------------------------------------------------------------------- public void testBidiClearByTailMap() { if (isRemoveSupported() == false) return; // extra test as other tests get complex SortedBidiMap sm = (SortedBidiMap) makeFullMap(); Iterator it = sm.keySet().iterator(); it.next(); it.next(); Object first = it.next(); Object fromKey = it.next(); Object second = it.next(); Object firstValue = sm.get(first); Object fromKeyValue = sm.get(fromKey); Object secondValue = sm.get(second); SortedMap sub = sm.tailMap(fromKey); int size = sm.size(); assertEquals(size - 3, sub.size()); sub.clear(); assertEquals(0, sub.size()); assertEquals(3, sm.size()); assertEquals(3, sm.inverseBidiMap().size()); assertEquals(true, sm.containsKey(first)); assertEquals(true, sm.containsValue(firstValue)); assertEquals(true, sm.inverseBidiMap().containsKey(firstValue)); assertEquals(true, sm.inverseBidiMap().containsValue(first)); assertEquals(false, sub.containsKey(first)); assertEquals(false, sub.containsValue(firstValue)); assertEquals(false, sm.containsKey(fromKey)); assertEquals(false, sm.containsValue(fromKeyValue)); assertEquals(false, sm.inverseBidiMap().containsKey(fromKeyValue)); assertEquals(false, sm.inverseBidiMap().containsValue(fromKey)); assertEquals(false, sub.containsKey(fromKey)); assertEquals(false, sub.containsValue(fromKeyValue)); assertEquals(false, sm.containsKey(second)); assertEquals(false, sm.containsValue(secondValue)); assertEquals(false, sm.inverseBidiMap().containsKey(secondValue)); assertEquals(false, sm.inverseBidiMap().containsValue(second)); assertEquals(false, sub.containsKey(second)); assertEquals(false, sub.containsValue(secondValue)); } //----------------------------------------------------------------------- public void testBidiRemoveByTailMap() { if (isRemoveSupported() == false) return; // extra test as other tests get complex SortedBidiMap sm = (SortedBidiMap) makeFullMap(); Iterator it = sm.keySet().iterator(); it.next(); it.next(); Object fromKey = it.next(); Object first = it.next(); Object second = it.next(); int size = sm.size(); SortedMap sub = sm.tailMap(fromKey); assertEquals(true, sm.containsKey(first)); assertEquals(true, sub.containsKey(first)); assertEquals(true, sm.containsKey(second)); assertEquals(true, sub.containsKey(second)); Object firstValue = sub.remove(first); assertEquals(size - 3, sub.size()); assertEquals(size - 1, sm.size()); assertEquals(size - 1, sm.inverseBidiMap().size()); assertEquals(false, sm.containsKey(first)); assertEquals(false, sm.containsValue(firstValue)); assertEquals(false, sm.inverseBidiMap().containsKey(firstValue)); assertEquals(false, sm.inverseBidiMap().containsValue(first)); assertEquals(false, sub.containsKey(first)); assertEquals(false, sub.containsValue(firstValue)); Object secondValue = sub.remove(second); assertEquals(size - 4, sub.size()); assertEquals(size - 2, sm.size()); assertEquals(size - 2, sm.inverseBidiMap().size()); assertEquals(false, sm.containsKey(second)); assertEquals(false, sm.containsValue(secondValue)); assertEquals(false, sm.inverseBidiMap().containsKey(secondValue)); assertEquals(false, sm.inverseBidiMap().containsValue(second)); assertEquals(false, sub.containsKey(second)); assertEquals(false, sub.containsValue(secondValue)); } //----------------------------------------------------------------------- public void testBidiRemoveByTailMapEntrySet() { if (isRemoveSupported() == false) return; // extra test as other tests get complex SortedBidiMap sm = (SortedBidiMap) makeFullMap(); Iterator it = sm.keySet().iterator(); it.next(); it.next(); Object fromKey = it.next(); Object first = it.next(); Object second = it.next(); int size = sm.size(); SortedMap sub = sm.tailMap(fromKey); Set set = sub.entrySet(); Iterator it2 = set.iterator(); Object fromEntry = it2.next(); Map.Entry firstEntry = cloneMapEntry((Map.Entry) it2.next()); Map.Entry secondEntry = cloneMapEntry((Map.Entry) it2.next()); assertEquals(true, sm.containsKey(first)); assertEquals(true, sub.containsKey(first)); assertEquals(true, set.contains(firstEntry)); assertEquals(true, sm.containsKey(second)); assertEquals(true, sub.containsKey(second)); assertEquals(true, set.contains(secondEntry)); set.remove(firstEntry); assertEquals(size - 3, sub.size()); assertEquals(size - 1, sm.size()); assertEquals(size - 1, sm.inverseBidiMap().size()); assertEquals(false, sm.containsKey(firstEntry.getKey())); assertEquals(false, sm.containsValue(firstEntry.getValue())); assertEquals(false, sm.inverseBidiMap().containsKey(firstEntry.getValue())); assertEquals(false, sm.inverseBidiMap().containsValue(firstEntry.getKey())); assertEquals(false, sub.containsKey(firstEntry.getKey())); assertEquals(false, sub.containsValue(firstEntry.getValue())); assertEquals(false, set.contains(firstEntry)); set.remove(secondEntry); assertEquals(size - 4, sub.size()); assertEquals(size - 2, sm.size()); assertEquals(size - 2, sm.inverseBidiMap().size()); assertEquals(false, sm.containsKey(secondEntry.getKey())); assertEquals(false, sm.containsValue(secondEntry.getValue())); assertEquals(false, sm.inverseBidiMap().containsKey(secondEntry.getValue())); assertEquals(false, sm.inverseBidiMap().containsValue(secondEntry.getKey())); assertEquals(false, sub.containsKey(secondEntry.getKey())); assertEquals(false, sub.containsValue(secondEntry.getValue())); assertEquals(false, set.contains(secondEntry)); } //----------------------------------------------------------------------- //----------------------------------------------------------------------- public void testBidiSubMapContains() { // extra test as other tests get complex SortedBidiMap sm = (SortedBidiMap) makeFullMap(); Iterator it = sm.keySet().iterator(); Object first = it.next(); Object fromKey = it.next(); Object second = it.next(); Object toKey = it.next(); Object third = it.next(); Object firstValue = sm.get(first); Object fromKeyValue = sm.get(fromKey); Object secondValue = sm.get(second); Object thirdValue = sm.get(third); SortedMap sub = sm.subMap(fromKey, toKey); assertEquals(2, sub.size()); assertEquals(true, sm.containsKey(first)); assertEquals(false, sub.containsKey(first)); assertEquals(true, sm.containsValue(firstValue)); assertEquals(false, sub.containsValue(firstValue)); assertEquals(true, sm.containsKey(fromKey)); assertEquals(true, sub.containsKey(fromKey)); assertEquals(true, sm.containsValue(fromKeyValue)); assertEquals(true, sub.containsValue(fromKeyValue)); assertEquals(true, sm.containsKey(second)); assertEquals(true, sub.containsKey(second)); assertEquals(true, sm.containsValue(secondValue)); assertEquals(true, sub.containsValue(secondValue)); assertEquals(true, sm.containsKey(third)); assertEquals(false, sub.containsKey(third)); assertEquals(true, sm.containsValue(thirdValue)); assertEquals(false, sub.containsValue(thirdValue)); } //----------------------------------------------------------------------- public void testBidiClearBySubMap() { if (isRemoveSupported() == false) return; // extra test as other tests get complex SortedBidiMap sm = (SortedBidiMap) makeFullMap(); Iterator it = sm.keySet().iterator(); it.next(); Object fromKey = it.next(); Object first = it.next(); Object second = it.next(); Object toKey = it.next(); Object fromKeyValue = sm.get(fromKey); Object firstValue = sm.get(first); Object secondValue = sm.get(second); Object toKeyValue = sm.get(toKey); SortedMap sub = sm.subMap(fromKey, toKey); int size = sm.size(); assertEquals(3, sub.size()); sub.clear(); assertEquals(0, sub.size()); assertEquals(size - 3, sm.size()); assertEquals(size - 3, sm.inverseBidiMap().size()); assertEquals(false, sm.containsKey(fromKey)); assertEquals(false, sm.containsValue(fromKeyValue)); assertEquals(false, sm.inverseBidiMap().containsKey(fromKeyValue)); assertEquals(false, sm.inverseBidiMap().containsValue(fromKey)); assertEquals(false, sub.containsKey(fromKey)); assertEquals(false, sub.containsValue(fromKeyValue)); assertEquals(false, sm.containsKey(first)); assertEquals(false, sm.containsValue(firstValue)); assertEquals(false, sm.inverseBidiMap().containsKey(firstValue)); assertEquals(false, sm.inverseBidiMap().containsValue(first)); assertEquals(false, sub.containsKey(first)); assertEquals(false, sub.containsValue(firstValue)); assertEquals(false, sm.containsKey(second)); assertEquals(false, sm.containsValue(secondValue)); assertEquals(false, sm.inverseBidiMap().containsKey(secondValue)); assertEquals(false, sm.inverseBidiMap().containsValue(second)); assertEquals(false, sub.containsKey(second)); assertEquals(false, sub.containsValue(secondValue)); assertEquals(true, sm.containsKey(toKey)); assertEquals(true, sm.containsValue(toKeyValue)); assertEquals(true, sm.inverseBidiMap().containsKey(toKeyValue)); assertEquals(true, sm.inverseBidiMap().containsValue(toKey)); assertEquals(false, sub.containsKey(toKey)); assertEquals(false, sub.containsValue(toKeyValue)); } //----------------------------------------------------------------------- public void testBidiRemoveBySubMap() { if (isRemoveSupported() == false) return; // extra test as other tests get complex SortedBidiMap sm = (SortedBidiMap) makeFullMap(); Iterator it = sm.keySet().iterator(); it.next(); it.next(); Object fromKey = it.next(); Object first = it.next(); Object second = it.next(); Object toKey = it.next(); int size = sm.size(); SortedMap sub = sm.subMap(fromKey, toKey); assertEquals(true, sm.containsKey(first)); assertEquals(true, sub.containsKey(first)); assertEquals(true, sm.containsKey(second)); assertEquals(true, sub.containsKey(second)); Object firstValue = sub.remove(first); assertEquals(2, sub.size()); assertEquals(size - 1, sm.size()); assertEquals(size - 1, sm.inverseBidiMap().size()); assertEquals(false, sm.containsKey(first)); assertEquals(false, sm.containsValue(firstValue)); assertEquals(false, sm.inverseBidiMap().containsKey(firstValue)); assertEquals(false, sm.inverseBidiMap().containsValue(first)); assertEquals(false, sub.containsKey(first)); assertEquals(false, sub.containsValue(firstValue)); Object secondValue = sub.remove(second); assertEquals(1, sub.size()); assertEquals(size - 2, sm.size()); assertEquals(size - 2, sm.inverseBidiMap().size()); assertEquals(false, sm.containsKey(second)); assertEquals(false, sm.containsValue(secondValue)); assertEquals(false, sm.inverseBidiMap().containsKey(secondValue)); assertEquals(false, sm.inverseBidiMap().containsValue(second)); assertEquals(false, sub.containsKey(second)); assertEquals(false, sub.containsValue(secondValue)); } //----------------------------------------------------------------------- public void testBidiRemoveBySubMapEntrySet() { if (isRemoveSupported() == false) return; // extra test as other tests get complex SortedBidiMap sm = (SortedBidiMap) makeFullMap(); Iterator it = sm.keySet().iterator(); it.next(); it.next(); Object fromKey = it.next(); Object first = it.next(); Object second = it.next(); Object toKey = it.next(); int size = sm.size(); SortedMap sub = sm.subMap(fromKey, toKey); Set set = sub.entrySet(); assertEquals(3, set.size()); Iterator it2 = set.iterator(); Object fromEntry = it2.next(); Map.Entry firstEntry = cloneMapEntry((Map.Entry) it2.next()); Map.Entry secondEntry = cloneMapEntry((Map.Entry) it2.next()); assertEquals(true, sm.containsKey(first)); assertEquals(true, sub.containsKey(first)); assertEquals(true, set.contains(firstEntry)); assertEquals(true, sm.containsKey(second)); assertEquals(true, sub.containsKey(second)); assertEquals(true, set.contains(secondEntry)); set.remove(firstEntry); assertEquals(2, sub.size()); assertEquals(size - 1, sm.size()); assertEquals(size - 1, sm.inverseBidiMap().size()); assertEquals(false, sm.containsKey(firstEntry.getKey())); assertEquals(false, sm.containsValue(firstEntry.getValue())); assertEquals(false, sm.inverseBidiMap().containsKey(firstEntry.getValue())); assertEquals(false, sm.inverseBidiMap().containsValue(firstEntry.getKey())); assertEquals(false, sub.containsKey(firstEntry.getKey())); assertEquals(false, sub.containsValue(firstEntry.getValue())); assertEquals(false, set.contains(firstEntry)); set.remove(secondEntry); assertEquals(1, sub.size()); assertEquals(size - 2, sm.size()); assertEquals(size - 2, sm.inverseBidiMap().size()); assertEquals(false, sm.containsKey(secondEntry.getKey())); assertEquals(false, sm.containsValue(secondEntry.getValue())); assertEquals(false, sm.inverseBidiMap().containsKey(secondEntry.getValue())); assertEquals(false, sm.inverseBidiMap().containsValue(secondEntry.getKey())); assertEquals(false, sub.containsKey(secondEntry.getKey())); assertEquals(false, sub.containsValue(secondEntry.getValue())); assertEquals(false, set.contains(secondEntry)); } //----------------------------------------------------------------------- public BulkTest bulkTestHeadMap() { return new AbstractTestSortedMap.TestHeadMap(this); } public BulkTest bulkTestTailMap() { return new AbstractTestSortedMap.TestTailMap(this); } public BulkTest bulkTestSubMap() { return new AbstractTestSortedMap.TestSubMap(this); } } ././@LongLink0000000000000000000000000000016400000000000011566 Lustar rootrootcollections-generic-4.01/src/test/org/apache/commons/collections15/bidimap/TestAbstractOrderedBidiMapDecorator.javacollections-generic-4.01/src/test/org/apache/commons/collections15/bidimap/TestAbstractOrderedBidiMa0000644000175000017500000000444410464140764034033 0ustar giovannigiovanni/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.bidimap; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.collections15.BidiMap; import org.apache.commons.collections15.OrderedBidiMap; import java.util.Map; import java.util.TreeMap; /** * Test class for AbstractOrderedBidiMapDecorator. * * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:44 $ */ public class TestAbstractOrderedBidiMapDecorator extends AbstractTestOrderedBidiMap { public TestAbstractOrderedBidiMapDecorator(String testName) { super(testName); } public static Test suite() { return new TestSuite(TestAbstractOrderedBidiMapDecorator.class); } public BidiMap makeEmptyBidiMap() { return new TestOrderedBidiMap(); } public Map makeConfirmedMap() { return new TreeMap(); } public boolean isAllowNullKey() { return false; } public boolean isAllowNullValue() { return false; } public boolean isSetValueSupported() { return true; } /** * Simple class to actually test. */ private static final class TestOrderedBidiMap extends AbstractOrderedBidiMapDecorator { private TestOrderedBidiMap inverse = null; public TestOrderedBidiMap() { super(new DualTreeBidiMap()); } public TestOrderedBidiMap(OrderedBidiMap map) { super(map); } public BidiMap inverseBidiMap() { if (inverse == null) { inverse = new TestOrderedBidiMap((OrderedBidiMap) getBidiMap().inverseBidiMap()); inverse.inverse = this; } return inverse; } } } collections-generic-4.01/src/test/org/apache/commons/collections15/bidimap/TestDualTreeBidiMap2.java0000644000175000017500000001072710464140756033654 0ustar giovannigiovanni/* * Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.bidimap; import junit.framework.Test; import junit.textui.TestRunner; import org.apache.commons.collections15.BidiMap; import org.apache.commons.collections15.BulkTest; import org.apache.commons.collections15.SortedBidiMap; import org.apache.commons.collections15.comparators.ComparableComparator; import org.apache.commons.collections15.comparators.ReverseComparator; import java.io.*; import java.util.*; /** * JUnit tests. * * @author Matthew Hawthorne * @author Stephen Colebourne * @author Matt Hall, John Watkinson, Jonas Van Poucke * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:44 $ */ public class TestDualTreeBidiMap2 extends AbstractTestSortedBidiMap { public static void main(String[] args) { TestRunner.run(suite()); } public static Test suite() { return BulkTest.makeSuite(TestDualTreeBidiMap2.class); } public TestDualTreeBidiMap2(String testName) { super(testName); } public BidiMap makeEmptyBidiMap() { return DualTreeBidiMap.createTwoWayBidiMap(new ReverseComparator(ComparableComparator.getInstance())); } public Map makeConfirmedMap() { return new TreeMap(new ReverseComparator(ComparableComparator.getInstance())); } public void testComparator() { resetEmpty(); SortedBidiMap bidi = (SortedBidiMap) map; assertNotNull(bidi.comparator()); assertTrue(bidi.comparator() instanceof ReverseComparator); } public void testSerializeDeserializeCheckComparator() throws Exception { SortedBidiMap obj = (SortedBidiMap) makeObject(); if (obj instanceof Serializable && isTestSerialization()) { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(buffer); out.writeObject(obj); out.close(); ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(buffer.toByteArray())); Object dest = in.readObject(); in.close(); SortedBidiMap bidi = (SortedBidiMap) dest; assertNotNull(obj.comparator()); assertNotNull(bidi.comparator()); assertTrue(bidi.comparator() instanceof ReverseComparator); } } public void testSortOrder() throws Exception { SortedBidiMap sm = (SortedBidiMap) makeFullMap(); // Sort by the comparator used in the makeEmptyBidiMap() method List newSortedKeys = Arrays.asList(getSampleKeys()); Collections.sort(newSortedKeys, new ReverseComparator(ComparableComparator.getInstance())); newSortedKeys = Collections.unmodifiableList(newSortedKeys); Iterator mapIter = sm.keySet().iterator(); Iterator expectedIter = newSortedKeys.iterator(); while (expectedIter.hasNext()) { Object expectedKey = expectedIter.next(); Object mapKey = mapIter.next(); assertNotNull("key in sorted list may not be null", expectedKey); assertNotNull("key in map may not be null", mapKey); assertEquals("key from sorted list and map must be equal", expectedKey, mapKey); } } public String getCompatibilityVersion() { return "3.Test2"; } /** * Override to prevent infinite recursion of tests. */ public String[] ignoredTests() { return new String[]{"TestDualTreeBidiMap2.bulkTestInverseMap.bulkTestInverseMap"}; } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk((java.io.Serializable) map, "D:/dev/collections15/data/test/DualTreeBidiMap.emptyCollection.version3.Test2.obj"); // resetFull(); // writeExternalFormToDisk((java.io.Serializable) map, "D:/dev/collections15/data/test/DualTreeBidiMap.fullCollection.version3.Test2.obj"); // } } collections-generic-4.01/src/test/org/apache/commons/collections15/bidimap/AbstractTestBidiMap.java0000644000175000017500000004725110464140755033631 0ustar giovannigiovanni/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.bidimap; import org.apache.commons.collections15.BidiMap; import org.apache.commons.collections15.BulkTest; import org.apache.commons.collections15.MapIterator; import org.apache.commons.collections15.iterators.AbstractTestMapIterator; import org.apache.commons.collections15.map.AbstractTestMap; import java.util.*; /** * Abstract test class for {@link BidiMap} methods and contracts. * * @author Matthew Hawthorne * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:44 $ */ public abstract class AbstractTestBidiMap extends AbstractTestMap { // Test data. private static final Object[][] entriesKV = new Object[][]{new Object[]{"key1", "value1"}, new Object[]{"key2", "value2"}, new Object[]{"key3", "value3"}}; private static final Object[][] entriesVK = new Object[][]{new Object[]{"value1", "key1"}, new Object[]{"value2", "key2"}, new Object[]{"value3", "key3"}}; protected final Object[][] entries; public AbstractTestBidiMap(String testName) { super(testName); entries = entriesKV; } public AbstractTestBidiMap() { super("Inverse"); entries = entriesVK; } //----------------------------------------------------------------------- /** * Implement to create an empty BidiMap. * * @return an empty BidiMap implementation. */ public abstract BidiMap makeEmptyBidiMap(); /** * Override to create a full BidiMap other than the default. * * @return a full BidiMap implementation. */ public BidiMap makeFullBidiMap() { final BidiMap map = makeEmptyBidiMap(); for (int i = 0; i < entries.length; i++) { map.put(entries[i][0], entries[i][1]); } return map; } /** * Override to return the empty BidiMap. */ public final Map makeEmptyMap() { return makeEmptyBidiMap(); } /** * Override to indicate to AbstractTestMap this is a BidiMap. */ public boolean isAllowDuplicateValues() { return false; } /** * Override as DualHashBidiMap didn't exist until version 3. */ public String getCompatibilityVersion() { return "3"; } // BidiPut //----------------------------------------------------------------------- public void testBidiPut() { if (isPutAddSupported() == false || isPutChangeSupported() == false) return; BidiMap map = makeEmptyBidiMap(); BidiMap inverse = map.inverseBidiMap(); assertEquals(0, map.size()); assertEquals(map.size(), inverse.size()); map.put("A", "B"); assertEquals(1, map.size()); assertEquals(map.size(), inverse.size()); assertEquals("B", map.get("A")); assertEquals("A", inverse.get("B")); map.put("A", "C"); assertEquals(1, map.size()); assertEquals(map.size(), inverse.size()); assertEquals("C", map.get("A")); assertEquals("A", inverse.get("C")); map.put("B", "C"); assertEquals(1, map.size()); assertEquals(map.size(), inverse.size()); assertEquals("C", map.get("B")); assertEquals("B", inverse.get("C")); map.put("E", "F"); assertEquals(2, map.size()); assertEquals(map.size(), inverse.size()); assertEquals("F", map.get("E")); assertEquals("E", inverse.get("F")); } /** * Verifies that {@link #map} is still equal to {@link #confirmed}. *

                  * This implementation checks the inverse map as well. */ public void verify() { verifyInverse(); super.verify(); } public void verifyInverse() { assertEquals(map.size(), ((BidiMap) map).inverseBidiMap().size()); Map map1 = new HashMap(map); Map map2 = new HashMap(((BidiMap) map).inverseBidiMap()); Set keys1 = map1.keySet(); Set keys2 = map2.keySet(); Collection values1 = map1.values(); Collection values2 = map2.values(); assertEquals(true, keys1.containsAll(values2)); assertEquals(true, values2.containsAll(keys1)); assertEquals(true, values1.containsAll(keys2)); assertEquals(true, keys2.containsAll(values1)); } // testGetKey //----------------------------------------------------------------------- public void testBidiGetKey() { doTestGetKey(makeFullBidiMap(), entries[0][0], entries[0][1]); } public void testBidiGetKeyInverse() { doTestGetKey(makeFullBidiMap().inverseBidiMap(), entries[0][1], entries[0][0]); } private final void doTestGetKey(BidiMap map, Object key, Object value) { assertEquals("Value not found for key.", value, map.get(key)); assertEquals("Key not found for value.", key, map.getKey(value)); } // testInverse //----------------------------------------------------------------------- public void testBidiInverse() { final BidiMap map = makeFullBidiMap(); final BidiMap inverseMap = map.inverseBidiMap(); assertSame("Inverse of inverse is not equal to original.", map, inverseMap.inverseBidiMap()); assertEquals("Value not found for key.", entries[0][0], inverseMap.get(entries[0][1])); assertEquals("Key not found for value.", entries[0][1], inverseMap.getKey(entries[0][0])); } //----------------------------------------------------------------------- public void testBidiModifyEntrySet() { if (isSetValueSupported() == false) return; modifyEntrySet(makeFullBidiMap()); modifyEntrySet(makeFullBidiMap().inverseBidiMap()); } private final void modifyEntrySet(BidiMap map) { // Gets first entry final Map.Entry entry = (Map.Entry) map.entrySet().iterator().next(); // Gets key and value final Object key = entry.getKey(); final Object oldValue = entry.getValue(); // Sets new value final Object newValue = "newValue"; entry.setValue(newValue); assertEquals("Modifying entrySet did not affect underlying Map.", newValue, map.get(key)); assertNull("Modifying entrySet did not affect inverse Map.", map.getKey(oldValue)); } //----------------------------------------------------------------------- public void testBidiClear() { if (isRemoveSupported() == false) { try { makeFullBidiMap().clear(); fail(); } catch (UnsupportedOperationException ex) { } return; } BidiMap map = makeFullBidiMap(); map.clear(); assertTrue("Map was not cleared.", map.isEmpty()); assertTrue("Inverse map was not cleared.", map.inverseBidiMap().isEmpty()); // Tests clear on inverse map = makeFullBidiMap().inverseBidiMap(); map.clear(); assertTrue("Map was not cleared.", map.isEmpty()); assertTrue("Inverse map was not cleared.", map.inverseBidiMap().isEmpty()); } //----------------------------------------------------------------------- public void testBidiRemove() { if (isRemoveSupported() == false) { try { makeFullBidiMap().remove(entries[0][0]); fail(); } catch (UnsupportedOperationException ex) { } try { makeFullBidiMap().removeValue(entries[0][1]); fail(); } catch (UnsupportedOperationException ex) { } return; } remove(makeFullBidiMap(), entries[0][0]); remove(makeFullBidiMap().inverseBidiMap(), entries[0][1]); removeValue(makeFullBidiMap(), entries[0][1]); removeValue(makeFullBidiMap().inverseBidiMap(), entries[0][0]); assertEquals(null, makeFullBidiMap().removeValue("NotPresent")); } private final void remove(BidiMap map, Object key) { final Object value = map.remove(key); assertTrue("Key was not removed.", !map.containsKey(key)); assertNull("Value was not removed.", map.getKey(value)); } private final void removeValue(BidiMap map, Object value) { final Object key = map.removeValue(value); assertTrue("Key was not removed.", !map.containsKey(key)); assertNull("Value was not removed.", map.getKey(value)); } //----------------------------------------------------------------------- public void testBidiKeySetValuesOrder() { resetFull(); Iterator keys = map.keySet().iterator(); Iterator values = map.values().iterator(); for (; keys.hasNext() && values.hasNext();) { Object key = keys.next(); Object value = values.next(); assertSame(map.get(key), value); } assertEquals(false, keys.hasNext()); assertEquals(false, values.hasNext()); } //----------------------------------------------------------------------- public void testBidiRemoveByKeySet() { if (isRemoveSupported() == false) return; removeByKeySet(makeFullBidiMap(), entries[0][0], entries[0][1]); removeByKeySet(makeFullBidiMap().inverseBidiMap(), entries[0][1], entries[0][0]); } private final void removeByKeySet(BidiMap map, Object key, Object value) { map.keySet().remove(key); assertTrue("Key was not removed.", !map.containsKey(key)); assertTrue("Value was not removed.", !map.containsValue(value)); assertTrue("Key was not removed from inverse map.", !map.inverseBidiMap().containsValue(key)); assertTrue("Value was not removed from inverse map.", !map.inverseBidiMap().containsKey(value)); } //----------------------------------------------------------------------- public void testBidiRemoveByEntrySet() { if (isRemoveSupported() == false) return; removeByEntrySet(makeFullBidiMap(), entries[0][0], entries[0][1]); removeByEntrySet(makeFullBidiMap().inverseBidiMap(), entries[0][1], entries[0][0]); } private final void removeByEntrySet(BidiMap map, Object key, Object value) { Map temp = new HashMap(); temp.put(key, value); map.entrySet().remove(temp.entrySet().iterator().next()); assertTrue("Key was not removed.", !map.containsKey(key)); assertTrue("Value was not removed.", !map.containsValue(value)); assertTrue("Key was not removed from inverse map.", !map.inverseBidiMap().containsValue(key)); assertTrue("Value was not removed from inverse map.", !map.inverseBidiMap().containsKey(value)); } //----------------------------------------------------------------------- public BulkTest bulkTestMapEntrySet() { return new TestBidiMapEntrySet(); } public class TestBidiMapEntrySet extends TestMapEntrySet { public TestBidiMapEntrySet() { super(); } public void testMapEntrySetIteratorEntrySetValueCrossCheck() { Object key1 = getSampleKeys()[0]; Object key2 = getSampleKeys()[1]; Object newValue1 = getNewSampleValues()[0]; Object newValue2 = getNewSampleValues()[1]; resetFull(); // explicitly get entries as sample values/keys are connected for some maps // such as BeanMap Iterator it = TestBidiMapEntrySet.this.collection.iterator(); Map.Entry entry1 = getEntry(it, key1); it = TestBidiMapEntrySet.this.collection.iterator(); Map.Entry entry2 = getEntry(it, key2); Iterator itConfirmed = TestBidiMapEntrySet.this.confirmed.iterator(); Map.Entry entryConfirmed1 = getEntry(itConfirmed, key1); itConfirmed = TestBidiMapEntrySet.this.confirmed.iterator(); Map.Entry entryConfirmed2 = getEntry(itConfirmed, key2); TestBidiMapEntrySet.this.verify(); if (isSetValueSupported() == false) { try { entry1.setValue(newValue1); } catch (UnsupportedOperationException ex) { } return; } // these checked in superclass entry1.setValue(newValue1); entryConfirmed1.setValue(newValue1); entry2.setValue(newValue2); entryConfirmed2.setValue(newValue2); // at this point // key1=newValue1, key2=newValue2 try { entry2.setValue(newValue1); // should remove key1 } catch (IllegalArgumentException ex) { return; // simplest way of dealing with tricky situation } entryConfirmed2.setValue(newValue1); AbstractTestBidiMap.this.confirmed.remove(key1); assertEquals(newValue1, entry2.getValue()); assertEquals(true, AbstractTestBidiMap.this.map.containsKey(entry2.getKey())); assertEquals(true, AbstractTestBidiMap.this.map.containsValue(newValue1)); assertEquals(newValue1, AbstractTestBidiMap.this.map.get(entry2.getKey())); assertEquals(false, AbstractTestBidiMap.this.map.containsKey(key1)); assertEquals(false, AbstractTestBidiMap.this.map.containsValue(newValue2)); TestBidiMapEntrySet.this.verify(); // check for ConcurrentModification it.next(); // if you fail here, maybe you should be throwing an IAE, see above if (isRemoveSupported()) { it.remove(); } } } public BulkTest bulkTestInverseMap() { return new TestInverseBidiMap(this); } public class TestInverseBidiMap extends AbstractTestBidiMap { final AbstractTestBidiMap main; public TestInverseBidiMap(AbstractTestBidiMap main) { super(); this.main = main; } public BidiMap makeEmptyBidiMap() { return main.makeEmptyBidiMap().inverseBidiMap(); } public BidiMap makeFullBidiMap() { return main.makeFullBidiMap().inverseBidiMap(); } public Map makeFullMap() { return ((BidiMap) main.makeFullMap()).inverseBidiMap(); } public Object[] getSampleKeys() { return main.getSampleValues(); } public Object[] getSampleValues() { return main.getSampleKeys(); } public String getCompatibilityVersion() { return main.getCompatibilityVersion(); } public boolean isAllowNullKey() { return main.isAllowNullKey(); } public boolean isAllowNullValue() { return main.isAllowNullValue(); } public boolean isPutAddSupported() { return main.isPutAddSupported(); } public boolean isPutChangeSupported() { return main.isPutChangeSupported(); } public boolean isSetValueSupported() { return main.isSetValueSupported(); } public boolean isRemoveSupported() { return main.isRemoveSupported(); } } //----------------------------------------------------------------------- public BulkTest bulkTestBidiMapIterator() { return new TestBidiMapIterator(); } public class TestBidiMapIterator extends AbstractTestMapIterator { public TestBidiMapIterator() { super("TestBidiMapIterator"); } public Object[] addSetValues() { return AbstractTestBidiMap.this.getNewSampleValues(); } public boolean supportsRemove() { return AbstractTestBidiMap.this.isRemoveSupported(); } public boolean supportsSetValue() { return AbstractTestBidiMap.this.isSetValueSupported(); } public MapIterator makeEmptyMapIterator() { resetEmpty(); return ((BidiMap) AbstractTestBidiMap.this.map).mapIterator(); } public MapIterator makeFullMapIterator() { resetFull(); return ((BidiMap) AbstractTestBidiMap.this.map).mapIterator(); } public Map getMap() { // assumes makeFullMapIterator() called first return AbstractTestBidiMap.this.map; } public Map getConfirmedMap() { // assumes makeFullMapIterator() called first return AbstractTestBidiMap.this.confirmed; } public void verify() { super.verify(); AbstractTestBidiMap.this.verify(); } } //----------------------------------------------------------------------- public void testBidiMapIteratorSet() { Object newValue1 = getOtherValues()[0]; Object newValue2 = getOtherValues()[1]; resetFull(); BidiMap bidi = (BidiMap) map; MapIterator it = bidi.mapIterator(); assertEquals(true, it.hasNext()); Object key1 = it.next(); if (isSetValueSupported() == false) { try { it.setValue(newValue1); fail(); } catch (UnsupportedOperationException ex) { } return; } it.setValue(newValue1); confirmed.put(key1, newValue1); assertSame(key1, it.getKey()); assertSame(newValue1, it.getValue()); assertEquals(true, bidi.containsKey(key1)); assertEquals(true, bidi.containsValue(newValue1)); assertEquals(newValue1, bidi.get(key1)); verify(); it.setValue(newValue1); // same value - should be OK confirmed.put(key1, newValue1); assertSame(key1, it.getKey()); assertSame(newValue1, it.getValue()); assertEquals(true, bidi.containsKey(key1)); assertEquals(true, bidi.containsValue(newValue1)); assertEquals(newValue1, bidi.get(key1)); verify(); Object key2 = it.next(); it.setValue(newValue2); confirmed.put(key2, newValue2); assertSame(key2, it.getKey()); assertSame(newValue2, it.getValue()); assertEquals(true, bidi.containsKey(key2)); assertEquals(true, bidi.containsValue(newValue2)); assertEquals(newValue2, bidi.get(key2)); verify(); // at this point // key1=newValue1, key2=newValue2 try { it.setValue(newValue1); // should remove key1 fail(); } catch (IllegalArgumentException ex) { return; // simplest way of dealing with tricky situation } confirmed.put(key2, newValue1); AbstractTestBidiMap.this.confirmed.remove(key1); assertEquals(newValue1, it.getValue()); assertEquals(true, bidi.containsKey(it.getKey())); assertEquals(true, bidi.containsValue(newValue1)); assertEquals(newValue1, bidi.get(it.getKey())); assertEquals(false, bidi.containsKey(key1)); assertEquals(false, bidi.containsValue(newValue2)); verify(); // check for ConcurrentModification it.next(); // if you fail here, maybe you should be throwing an IAE, see above if (isRemoveSupported()) { it.remove(); } } } collections-generic-4.01/src/test/org/apache/commons/collections15/bidimap/TestTreeBidiMap.java0000644000175000017500000000360610464140755032761 0ustar giovannigiovanni/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.bidimap; import junit.framework.Test; import junit.textui.TestRunner; import org.apache.commons.collections15.BidiMap; import org.apache.commons.collections15.BulkTest; import java.util.Map; import java.util.TreeMap; /** * JUnit tests. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:44 $ */ public class TestTreeBidiMap extends AbstractTestOrderedBidiMap { public static void main(String[] args) { TestRunner.run(suite()); } public static Test suite() { return BulkTest.makeSuite(TestTreeBidiMap.class); } public TestTreeBidiMap(String testName) { super(testName); } public BidiMap makeEmptyBidiMap() { return new TreeBidiMap(); } public Map makeConfirmedMap() { return new TreeMap(); } /** * Override to prevent infinite recursion of tests. */ public String[] ignoredTests() { return new String[]{"TestTreeBidiMap.bulkTestInverseMap.bulkTestInverseMap"}; } public boolean isAllowNullKey() { return false; } public boolean isAllowNullValue() { return false; } public boolean isSetValueSupported() { return false; } } collections-generic-4.01/src/test/org/apache/commons/collections15/bidimap/TestDualTreeBidiMap.java0000644000175000017500000000377010464140760033565 0ustar giovannigiovanni/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.bidimap; import junit.framework.Test; import junit.textui.TestRunner; import org.apache.commons.collections15.BidiMap; import org.apache.commons.collections15.BulkTest; /** * JUnit tests. * * @author Matthew Hawthorne * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:44 $ */ public class TestDualTreeBidiMap extends AbstractTestSortedBidiMap { public static void main(String[] args) { TestRunner.run(suite()); } public static Test suite() { return BulkTest.makeSuite(TestDualTreeBidiMap.class); } public TestDualTreeBidiMap(String testName) { super(testName); } public BidiMap makeEmptyBidiMap() { return new DualTreeBidiMap(); } /** * Override to prevent infinite recursion of tests. */ public String[] ignoredTests() { return new String[]{"TestDualTreeBidiMap.bulkTestInverseMap.bulkTestInverseMap"}; } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk((Serializable) map, "D:/dev/collections15/data/test/DualTreeBidiMap.emptyCollection.version3.obj"); // resetFull(); // writeExternalFormToDisk((Serializable) map, "D:/dev/collections15/data/test/DualTreeBidiMap.fullCollection.version3.obj"); // } } collections-generic-4.01/src/test/org/apache/commons/collections15/bidimap/TestAll.java0000644000175000017500000000341110464140760031332 0ustar giovannigiovanni/* * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.bidimap; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * Entry point for tests. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:44 $ * @since Commons Collections 3.0 */ public class TestAll extends TestCase { public TestAll(String testName) { super(testName); } public static void main(String args[]) { String[] testCaseName = {TestAll.class.getName()}; junit.textui.TestRunner.main(testCaseName); } public static Test suite() { TestSuite suite = new TestSuite(); suite.addTest(TestDualHashBidiMap.suite()); suite.addTest(TestDualTreeBidiMap.suite()); suite.addTest(TestDualTreeBidiMap2.suite()); suite.addTest(TestTreeBidiMap.suite()); suite.addTest(TestAbstractOrderedBidiMapDecorator.suite()); suite.addTest(TestUnmodifiableBidiMap.suite()); suite.addTest(TestUnmodifiableOrderedBidiMap.suite()); suite.addTest(TestUnmodifiableSortedBidiMap.suite()); return suite; } } collections-generic-4.01/src/test/org/apache/commons/collections15/bidimap/TestDualHashBidiMap.java0000644000175000017500000000376210464140762033554 0ustar giovannigiovanni/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.bidimap; import junit.framework.Test; import junit.textui.TestRunner; import org.apache.commons.collections15.BidiMap; import org.apache.commons.collections15.BulkTest; /** * JUnit tests. * * @author Matthew Hawthorne * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:44 $ */ public class TestDualHashBidiMap extends AbstractTestBidiMap { public static void main(String[] args) { TestRunner.run(suite()); } public static Test suite() { return BulkTest.makeSuite(TestDualHashBidiMap.class); } public TestDualHashBidiMap(String testName) { super(testName); } public BidiMap makeEmptyBidiMap() { return new DualHashBidiMap(); } /** * Override to prevent infinite recursion of tests. */ public String[] ignoredTests() { return new String[]{"TestDualHashBidiMap.bulkTestInverseMap.bulkTestInverseMap"}; } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk((Serializable) map, "D:/dev/collections15/data/test/DualHashBidiMap.emptyCollection.version3.obj"); // resetFull(); // writeExternalFormToDisk((Serializable) map, "D:/dev/collections15/data/test/DualHashBidiMap.fullCollection.version3.obj"); // } } ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootcollections-generic-4.01/src/test/org/apache/commons/collections15/bidimap/TestUnmodifiableBidiMap.javacollections-generic-4.01/src/test/org/apache/commons/collections15/bidimap/TestUnmodifiableBidiMap.j0000644000175000017500000000455610464140755033775 0ustar giovannigiovanni/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.bidimap; import junit.framework.Test; import junit.textui.TestRunner; import org.apache.commons.collections15.BidiMap; import org.apache.commons.collections15.BulkTest; import java.util.HashMap; import java.util.Map; /** * JUnit tests. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:44 $ */ public class TestUnmodifiableBidiMap extends AbstractTestBidiMap { public static void main(String[] args) { TestRunner.run(suite()); } public static Test suite() { return BulkTest.makeSuite(TestUnmodifiableBidiMap.class); } public TestUnmodifiableBidiMap(String testName) { super(testName); } public BidiMap makeEmptyBidiMap() { return UnmodifiableBidiMap.decorate(new DualHashBidiMap()); } public BidiMap makeFullBidiMap() { BidiMap bidi = new DualHashBidiMap(); for (int i = 0; i < entries.length; i++) { bidi.put(entries[i][0], entries[i][1]); } return UnmodifiableBidiMap.decorate(bidi); } public Map makeFullMap() { BidiMap bidi = new DualHashBidiMap(); addSampleMappings(bidi); return UnmodifiableBidiMap.decorate(bidi); } public Map makeConfirmedMap() { return new HashMap(); } /** * Override to prevent infinite recursion of tests. */ public String[] ignoredTests() { return new String[]{"TestUnmodifiableBidiMap.bulkTestInverseMap.bulkTestInverseMap"}; } public boolean isPutAddSupported() { return false; } public boolean isPutChangeSupported() { return false; } public boolean isRemoveSupported() { return false; } } ././@LongLink0000000000000000000000000000015600000000000011567 Lustar rootrootcollections-generic-4.01/src/test/org/apache/commons/collections15/bidimap/TestUnmodifiableSortedBidiMap.javacollections-generic-4.01/src/test/org/apache/commons/collections15/bidimap/TestUnmodifiableSortedBid0000644000175000017500000000560710464140754034114 0ustar giovannigiovanni/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.bidimap; import junit.framework.Test; import junit.textui.TestRunner; import org.apache.commons.collections15.BidiMap; import org.apache.commons.collections15.BulkTest; import org.apache.commons.collections15.SortedBidiMap; import java.util.Map; import java.util.TreeMap; /** * JUnit tests. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:44 $ */ public class TestUnmodifiableSortedBidiMap extends AbstractTestSortedBidiMap { public static void main(String[] args) { TestRunner.run(suite()); } public static Test suite() { return BulkTest.makeSuite(TestUnmodifiableSortedBidiMap.class); } public TestUnmodifiableSortedBidiMap(String testName) { super(testName); } //----------------------------------------------------------------------- public BidiMap makeEmptyBidiMap() { return UnmodifiableSortedBidiMap.decorate(new DualTreeBidiMap()); } public BidiMap makeFullBidiMap() { SortedBidiMap bidi = new DualTreeBidiMap(); for (int i = 0; i < entries.length; i++) { bidi.put(entries[i][0], entries[i][1]); } return UnmodifiableSortedBidiMap.decorate(bidi); } public Map makeFullMap() { SortedBidiMap bidi = new DualTreeBidiMap(); addSampleMappings(bidi); return UnmodifiableSortedBidiMap.decorate(bidi); } public Map makeConfirmedMap() { return new TreeMap(); } public boolean isSubMapViewsSerializable() { // TreeMap sub map views have a bug in deserialization. return false; } public String[] ignoredTests() { // Override to prevent infinite recursion of tests. return new String[]{"TestUnmodifiableSortedBidiMap.bulkTestInverseMap.bulkTestInverseMap"}; } //----------------------------------------------------------------------- public boolean isAllowNullKey() { return false; } public boolean isAllowNullValue() { return false; } public boolean isPutAddSupported() { return false; } public boolean isPutChangeSupported() { return false; } public boolean isRemoveSupported() { return false; } } ././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootcollections-generic-4.01/src/test/org/apache/commons/collections15/bidimap/AbstractTestOrderedBidiMap.javacollections-generic-4.01/src/test/org/apache/commons/collections15/bidimap/AbstractTestOrderedBidiMa0000644000175000017500000001442710464140755034035 0ustar giovannigiovanni/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.bidimap; import org.apache.commons.collections15.BulkTest; import org.apache.commons.collections15.MapIterator; import org.apache.commons.collections15.OrderedBidiMap; import org.apache.commons.collections15.iterators.AbstractTestMapIterator; import java.util.*; /** * Abstract test class for {@link OrderedBidiMap} methods and contracts. * * @author Matthew Hawthorne * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:44 $ */ public abstract class AbstractTestOrderedBidiMap extends AbstractTestBidiMap { public AbstractTestOrderedBidiMap(String testName) { super(testName); } public AbstractTestOrderedBidiMap() { super(); } //----------------------------------------------------------------------- public void testFirstKey() { resetEmpty(); OrderedBidiMap bidi = (OrderedBidiMap) map; try { bidi.firstKey(); fail(); } catch (NoSuchElementException ex) { } resetFull(); bidi = (OrderedBidiMap) map; Object confirmedFirst = confirmed.keySet().iterator().next(); assertEquals(confirmedFirst, bidi.firstKey()); } public void testLastKey() { resetEmpty(); OrderedBidiMap bidi = (OrderedBidiMap) map; try { bidi.lastKey(); fail(); } catch (NoSuchElementException ex) { } resetFull(); bidi = (OrderedBidiMap) map; Object confirmedLast = null; for (Iterator it = confirmed.keySet().iterator(); it.hasNext();) { confirmedLast = it.next(); } assertEquals(confirmedLast, bidi.lastKey()); } //----------------------------------------------------------------------- public void testNextKey() { resetEmpty(); OrderedBidiMap bidi = (OrderedBidiMap) map; assertEquals(null, bidi.nextKey(getOtherKeys()[0])); if (isAllowNullKey() == false) { try { assertEquals(null, bidi.nextKey(null)); // this is allowed too } catch (NullPointerException ex) { } } else { assertEquals(null, bidi.nextKey(null)); } resetFull(); bidi = (OrderedBidiMap) map; Iterator it = confirmed.keySet().iterator(); Object confirmedLast = it.next(); while (it.hasNext()) { Object confirmedObject = it.next(); assertEquals(confirmedObject, bidi.nextKey(confirmedLast)); confirmedLast = confirmedObject; } assertEquals(null, bidi.nextKey(confirmedLast)); if (isAllowNullKey() == false) { try { bidi.nextKey(null); fail(); } catch (NullPointerException ex) { } } else { assertEquals(null, bidi.nextKey(null)); } } public void testPreviousKey() { resetEmpty(); OrderedBidiMap bidi = (OrderedBidiMap) map; assertEquals(null, bidi.previousKey(getOtherKeys()[0])); if (isAllowNullKey() == false) { try { assertEquals(null, bidi.previousKey(null)); // this is allowed too } catch (NullPointerException ex) { } } else { assertEquals(null, bidi.previousKey(null)); } resetFull(); bidi = (OrderedBidiMap) map; List list = new ArrayList(confirmed.keySet()); Collections.reverse(list); Iterator it = list.iterator(); Object confirmedLast = it.next(); while (it.hasNext()) { Object confirmedObject = it.next(); assertEquals(confirmedObject, bidi.previousKey(confirmedLast)); confirmedLast = confirmedObject; } assertEquals(null, bidi.previousKey(confirmedLast)); if (isAllowNullKey() == false) { try { bidi.previousKey(null); fail(); } catch (NullPointerException ex) { } } else { assertEquals(null, bidi.previousKey(null)); } } //----------------------------------------------------------------------- public BulkTest bulkTestOrderedMapIterator() { return new TestBidiOrderedMapIterator(); } public class TestBidiOrderedMapIterator extends AbstractTestMapIterator { public TestBidiOrderedMapIterator() { super("TestBidiOrderedMapIterator"); } public Object[] addSetValues() { return AbstractTestOrderedBidiMap.this.getNewSampleValues(); } public boolean supportsRemove() { return AbstractTestOrderedBidiMap.this.isRemoveSupported(); } public boolean supportsSetValue() { return AbstractTestOrderedBidiMap.this.isSetValueSupported(); } public MapIterator makeEmptyMapIterator() { resetEmpty(); return ((OrderedBidiMap) AbstractTestOrderedBidiMap.this.map).orderedMapIterator(); } public MapIterator makeFullMapIterator() { resetFull(); return ((OrderedBidiMap) AbstractTestOrderedBidiMap.this.map).orderedMapIterator(); } public Map getMap() { // assumes makeFullMapIterator() called first return AbstractTestOrderedBidiMap.this.map; } public Map getConfirmedMap() { // assumes makeFullMapIterator() called first return AbstractTestOrderedBidiMap.this.confirmed; } public void verify() { super.verify(); AbstractTestOrderedBidiMap.this.verify(); } } } ././@LongLink0000000000000000000000000000015700000000000011570 Lustar rootrootcollections-generic-4.01/src/test/org/apache/commons/collections15/bidimap/TestUnmodifiableOrderedBidiMap.javacollections-generic-4.01/src/test/org/apache/commons/collections15/bidimap/TestUnmodifiableOrderedBi0000644000175000017500000000515010464140763034065 0ustar giovannigiovanni/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.bidimap; import junit.framework.Test; import junit.textui.TestRunner; import org.apache.commons.collections15.BidiMap; import org.apache.commons.collections15.BulkTest; import org.apache.commons.collections15.OrderedBidiMap; import java.util.Map; import java.util.TreeMap; /** * JUnit tests. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:44 $ */ public class TestUnmodifiableOrderedBidiMap extends AbstractTestOrderedBidiMap { public static void main(String[] args) { TestRunner.run(suite()); } public static Test suite() { return BulkTest.makeSuite(TestUnmodifiableOrderedBidiMap.class); } public TestUnmodifiableOrderedBidiMap(String testName) { super(testName); } public BidiMap makeEmptyBidiMap() { return UnmodifiableOrderedBidiMap.decorate(new TreeBidiMap()); } public BidiMap makeFullBidiMap() { OrderedBidiMap bidi = new TreeBidiMap(); for (int i = 0; i < entries.length; i++) { bidi.put(entries[i][0], entries[i][1]); } return UnmodifiableOrderedBidiMap.decorate(bidi); } public Map makeFullMap() { OrderedBidiMap bidi = new TreeBidiMap(); addSampleMappings(bidi); return UnmodifiableOrderedBidiMap.decorate(bidi); } public Map makeConfirmedMap() { return new TreeMap(); } /** * Override to prevent infinite recursion of tests. */ public String[] ignoredTests() { return new String[]{"TestUnmodifiableOrderedBidiMap.bulkTestInverseMap.bulkTestInverseMap"}; } public boolean isAllowNullKey() { return false; } public boolean isAllowNullValue() { return false; } public boolean isPutAddSupported() { return false; } public boolean isPutChangeSupported() { return false; } public boolean isRemoveSupported() { return false; } } collections-generic-4.01/src/test/org/apache/commons/collections15/TestFastHashMap.java0000644000175000017500000000276510464140755031373 0ustar giovannigiovanni/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15; import junit.framework.Test; import org.apache.commons.collections15.map.AbstractTestMap; import org.apache.commons.collections15.map.FastHashMap; import java.util.Map; /** * Tests FastHashMap. * * @author Matt Hall, John Watkinson, Jason van Zyl * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:39 $ */ public class TestFastHashMap extends AbstractTestMap { public TestFastHashMap(String testName) { super(testName); } public static Test suite() { return BulkTest.makeSuite(TestFastHashMap.class); } public static void main(String args[]) { String[] testCaseName = {TestFastHashMap.class.getName()}; junit.textui.TestRunner.main(testCaseName); } public Map makeEmptyMap() { FastHashMap fhm = new FastHashMap(); fhm.setFast(false); return (fhm); } } collections-generic-4.01/src/test/org/apache/commons/collections15/TestAll.java0000644000175000017500000000645410464140760027737 0ustar giovannigiovanni/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.apache.commons.collections15.list.TestCursorableLinkedList; import org.apache.commons.collections15.bag.TestHashBag; import org.apache.commons.collections15.bag.TestTreeBag; import org.apache.commons.collections15.map.TestLRUMap; import org.apache.commons.collections15.map.TestReferenceMap; import org.apache.commons.collections15.map.TestStaticBucketMap; import org.apache.commons.collections15.buffer.TestUnboundedFifoBuffer; /** * Entry point for all Collections package tests. * * @author Rodney Waldhoff * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:39 $ */ public class TestAll extends TestCase { public TestAll(String testName) { super(testName); } public static Test suite() { TestSuite suite = new TestSuite(); suite.addTest(TestBagUtils.suite()); suite.addTest(TestClosureUtils.suite()); suite.addTest(TestCollectionUtils.suite()); suite.addTest(TestBufferUtils.suite()); suite.addTest(TestEnumerationUtils.suite()); suite.addTest(TestFactoryUtils.suite()); suite.addTest(TestListUtils.suite()); suite.addTest(TestMapUtils.suite()); suite.addTest(TestPredicateUtils.suite()); suite.addTest(TestSetUtils.suite()); suite.addTest(TestTransformerUtils.suite()); suite.addTest(TestArrayStack.suite()); suite.addTest(TestBeanMap.suite()); //suite.addTest(TestBinaryHeap.suite()); suite.addTest(TestCursorableLinkedList.suite()); //suite.addTest(TestDoubleOrderedMap.suite()); suite.addTest(TestExtendedProperties.suite()); suite.addTest(TestFastArrayList.suite()); suite.addTest(TestFastArrayList1.suite()); suite.addTest(TestFastHashMap.suite()); suite.addTest(TestFastHashMap1.suite()); suite.addTest(TestFastTreeMap.suite()); suite.addTest(TestFastTreeMap1.suite()); suite.addTest(TestHashBag.suite()); suite.addTest(TestIteratorUtils.suite()); suite.addTest(TestLRUMap.suite()); suite.addTest(TestMultiHashMap.suite()); suite.addTest(TestReferenceMap.suite()); //suite.addTest(TestSequencedHashMap.suite()); suite.addTest(TestStaticBucketMap.suite()); suite.addTest(TestTreeBag.suite()); suite.addTest(TestUnboundedFifoBuffer.suite()); return suite; } public static void main(String args[]) { String[] testCaseName = {TestAll.class.getName()}; junit.textui.TestRunner.main(testCaseName); } } collections-generic-4.01/src/test/org/apache/commons/collections15/TestBagUtils.java0000644000175000017500000001631410464140764030741 0ustar giovannigiovanni/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15; import junit.framework.Test; import org.apache.commons.collections15.bag.*; /** * Tests for BagUtils factory methods. * * @author Matt Hall, John Watkinson, Phil Steitz * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:39 $ */ public class TestBagUtils extends BulkTest { public TestBagUtils(String name) { super(name); } public static Test suite() { return BulkTest.makeSuite(TestBagUtils.class); } //---------------------------------------------------------------------- protected Class stringClass = this.getName().getClass(); protected Predicate truePredicate = PredicateUtils.truePredicate(); protected Transformer nopTransformer = TransformerUtils.nopTransformer(); //---------------------------------------------------------------------- public void testSynchronizedBag() { Bag bag = BagUtils.synchronizedBag(new HashBag()); assertTrue("Returned object should be a SynchronizedBag.", bag instanceof SynchronizedBag); try { bag = BagUtils.synchronizedBag(null); fail("Expecting IllegalArgumentException for null bag."); } catch (IllegalArgumentException ex) { // expected } } public void testUnmodifiableBag() { Bag bag = BagUtils.unmodifiableBag(new HashBag()); assertTrue("Returned object should be an UnmodifiableBag.", bag instanceof UnmodifiableBag); try { bag = BagUtils.unmodifiableBag(null); fail("Expecting IllegalArgumentException for null bag."); } catch (IllegalArgumentException ex) { // expected } } public void testPredicatedBag() { Bag bag = BagUtils.predicatedBag(new HashBag(), truePredicate); assertTrue("Returned object should be a PredicatedBag.", bag instanceof PredicatedBag); try { bag = BagUtils.predicatedBag(null, truePredicate); fail("Expecting IllegalArgumentException for null bag."); } catch (IllegalArgumentException ex) { // expected } try { bag = BagUtils.predicatedBag(new HashBag(), null); fail("Expecting IllegalArgumentException for null predicate."); } catch (IllegalArgumentException ex) { // expected } } public void testTypedBag() { Bag bag = BagUtils.typedBag(new HashBag(), stringClass); assertTrue("Returned object should be a TypedBag.", bag instanceof PredicatedBag); try { bag = BagUtils.typedBag(null, stringClass); fail("Expecting IllegalArgumentException for null bag."); } catch (IllegalArgumentException ex) { // expected } try { bag = BagUtils.typedBag(new HashBag(), null); fail("Expecting IllegalArgumentException for null type."); } catch (IllegalArgumentException ex) { // expected } } public void testTransformedBag() { Bag bag = BagUtils.transformedBag(new HashBag(), nopTransformer); assertTrue("Returned object should be an TransformedBag.", bag instanceof TransformedBag); try { bag = BagUtils.transformedBag(null, nopTransformer); fail("Expecting IllegalArgumentException for null bag."); } catch (IllegalArgumentException ex) { // expected } try { bag = BagUtils.transformedBag(new HashBag(), null); fail("Expecting IllegalArgumentException for null transformer."); } catch (IllegalArgumentException ex) { // expected } } public void testSynchronizedSortedBag() { Bag bag = BagUtils.synchronizedSortedBag(new TreeBag()); assertTrue("Returned object should be a SynchronizedSortedBag.", bag instanceof SynchronizedSortedBag); try { bag = BagUtils.synchronizedSortedBag(null); fail("Expecting IllegalArgumentException for null bag."); } catch (IllegalArgumentException ex) { // expected } } public void testUnmodifiableSortedBag() { Bag bag = BagUtils.unmodifiableSortedBag(new TreeBag()); assertTrue("Returned object should be an UnmodifiableSortedBag.", bag instanceof UnmodifiableSortedBag); try { bag = BagUtils.unmodifiableSortedBag(null); fail("Expecting IllegalArgumentException for null bag."); } catch (IllegalArgumentException ex) { // expected } } public void testPredicatedSortedBag() { Bag bag = BagUtils.predicatedSortedBag(new TreeBag(), truePredicate); assertTrue("Returned object should be a PredicatedSortedBag.", bag instanceof PredicatedSortedBag); try { bag = BagUtils.predicatedSortedBag(null, truePredicate); fail("Expecting IllegalArgumentException for null bag."); } catch (IllegalArgumentException ex) { // expected } try { bag = BagUtils.predicatedSortedBag(new TreeBag(), null); fail("Expecting IllegalArgumentException for null predicate."); } catch (IllegalArgumentException ex) { // expected } } public void testTypedSortedBag() { Bag bag = BagUtils.typedSortedBag(new TreeBag(), stringClass); assertTrue("Returned object should be a TypedSortedBag.", bag instanceof PredicatedSortedBag); try { bag = BagUtils.typedSortedBag(null, stringClass); fail("Expecting IllegalArgumentException for null bag."); } catch (IllegalArgumentException ex) { // expected } try { bag = BagUtils.typedSortedBag(new TreeBag(), null); fail("Expecting IllegalArgumentException for null type."); } catch (IllegalArgumentException ex) { // expected } } public void testTransformedSortedBag() { Bag bag = BagUtils.transformedSortedBag(new TreeBag(), nopTransformer); assertTrue("Returned object should be an TransformedSortedBag", bag instanceof TransformedSortedBag); try { bag = BagUtils.transformedSortedBag(null, nopTransformer); fail("Expecting IllegalArgumentException for null bag."); } catch (IllegalArgumentException ex) { // expected } try { bag = BagUtils.transformedSortedBag(new TreeBag(), null); fail("Expecting IllegalArgumentException for null transformer."); } catch (IllegalArgumentException ex) { // expected } } } collections-generic-4.01/src/test/org/apache/commons/collections15/BulkTest.java0000644000175000017500000003524310464140764030126 0ustar giovannigiovanni/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15; import junit.framework.TestCase; import junit.framework.TestSuite; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * A {@link TestCase} that can define both simple and bulk test methods. *

                  * A simple test method is the type of test traditionally * supplied by by {@link TestCase}. To define a simple test, create a public * no-argument method whose name starts with "test". You can specify the * the name of simple test in the constructor of BulkTest; * a subsequent call to {@link TestCase#run} will run that simple test. *

                  * A bulk test method, on the other hand, returns a new instance * of BulkTest, which can itself define new simple and bulk * test methods. By using the {@link #makeSuite} method, you can * automatically create a hierarchal suite of tests and child bulk tests. *

                  * For instance, consider the following two classes: *

                  *

                   * public class TestSet extends BulkTest {
                   * 

                  * private Set set; *

                  * public TestSet(Set set) { * this.set = set; * } *

                  * public void testContains() { * boolean r = set.contains(set.iterator().next())); * assertTrue("Set should contain first element, r); * } *

                  * public void testClear() { * set.clear(); * assertTrue("Set should be empty after clear", set.isEmpty()); * } * } *

                  *

                  * public class TestHashMap extends BulkTest { *

                  * private Map makeFullMap() { * HashMap result = new HashMap(); * result.put("1", "One"); * result.put("2", "Two"); * return result; * } *

                  * public void testClear() { * Map map = makeFullMap(); * map.clear(); * assertTrue("Map empty after clear", map.isEmpty()); * } *

                  * public BulkTest bulkTestKeySet() { * return new TestSet(makeFullMap().keySet()); * } *

                  * public BulkTest bulkTestEntrySet() { * return new TestSet(makeFullMap().entrySet()); * } * } *

                  *

                  * In the above examples, TestSet defines two * simple test methods and no bulk test methods; TestHashMap * defines one simple test method and two bulk test methods. When * makeSuite(TestHashMap.class).run is executed, * five simple test methods will be run, in this order:

                  *

                  *

                    *
                  1. TestHashMap.testClear() *
                  2. TestHashMap.bulkTestKeySet().testContains(); *
                  3. TestHashMap.bulkTestKeySet().testClear(); *
                  4. TestHashMap.bulkTestEntrySet().testContains(); *
                  5. TestHashMap.bulkTestEntrySet().testClear(); *
                  *

                  * In the graphical junit test runners, the tests would be displayed in * the following tree:

                  *

                  *

                    *
                  • TestHashMap
                  • *
                      *
                    • testClear *
                    • bulkTestKeySet *
                        *
                      • testContains *
                      • testClear *
                      *
                    • bulkTestEntrySet *
                        *
                      • testContains *
                      • testClear *
                      *
                    *
                  *

                  * A subclass can override a superclass's bulk test by * returning null from the bulk test method. If you only * want to override specific simple tests within a bulk test, use the * {@link #ignoredTests} method.

                  *

                  * Note that if you want to use the bulk test methods, you must * define your suite() method to use {@link #makeSuite}. * The ordinary {@link TestSuite} constructor doesn't know how to * interpret bulk test methods. * * @author Matt Hall, John Watkinson, Paul Jack * @version $Id: BulkTest.java,v 1.1 2005/10/11 17:05:39 pents90 Exp $ */ public class BulkTest extends TestCase implements Cloneable { // Note: BulkTest is Cloneable to make it easier to construct // BulkTest instances for simple test methods that are defined in // anonymous inner classes. Basically we don't have to worry about // finding weird constructors. (And even if we found them, technically // it'd be illegal for anyone but the outer class to invoke them). // Given one BulkTest instance, we can just clone it and reset the // method name for every simple test it defines. /** * The full name of this bulk test instance. This is the full name * that is compared to {@link #ignoredTests} to see if this * test should be ignored. It's also displayed in the text runner * to ease debugging. */ String verboseName; /** * Constructs a new BulkTest instance that will run the * specified simple test. * * @param name the name of the simple test method to run */ public BulkTest(String name) { super(name); this.verboseName = getClass().getName(); } /** * Creates a clone of this BulkTest.

                  * * @return a clone of this BulkTest */ public Object clone() { try { return super.clone(); } catch (CloneNotSupportedException e) { throw new Error(); // should never happen } } /** * Returns an array of test names to ignore.

                  *

                  * If a test that's defined by this BulkTest or * by one of its bulk test methods has a name that's in the returned * array, then that simple test will not be executed.

                  *

                  * A test's name is formed by taking the class name of the * root BulkTest, eliminating the package name, then * appending the names of any bulk test methods that were invoked * to get to the simple test, and then appending the simple test * method name. The method names are delimited by periods: *

                  *

                       *  TestHashMap.bulkTestEntrySet.testClear
                       *  
                  *

                  * is the name of one of the simple tests defined in the sample classes * described above. If the sample TestHashMap class * included this method: *

                  *

                       *  public String[] ignoredTests() {
                       *      return new String[] { "TestHashMap.bulkTestEntrySet.testClear" };
                       *  }
                       *  
                  *

                  * then the entry set's clear method wouldn't be tested, but the key * set's clear method would. * * @return an array of the names of tests to ignore, or null if * no tests should be ignored */ public String[] ignoredTests() { return null; } /** * Returns the display name of this BulkTest. * * @return the display name of this BulkTest */ public String toString() { return getName() + "(" + verboseName + ") "; } /** * Returns a {@link TestSuite} for testing all of the simple tests * and all the bulk tests defined by the given class.

                  *

                  * The class is examined for simple and bulk test methods; any child * bulk tests are also examined recursively; and the results are stored * in a hierarchal {@link TestSuite}.

                  *

                  * The given class must be a subclass of BulkTest and must * not be abstract.

                  * * @param c the class to examine for simple and bulk tests * @return a {@link TestSuite} containing all the simple and bulk tests * defined by that class */ public static TestSuite makeSuite(Class c) { if (Modifier.isAbstract(c.getModifiers())) { throw new IllegalArgumentException("Class must not be abstract."); } if (!BulkTest.class.isAssignableFrom(c)) { throw new IllegalArgumentException("Class must extend BulkTest."); } return new BulkTestSuiteMaker(c).make(); } } // It was easier to use a separate class to do all the reflection stuff // for making the TestSuite instances. Having permanent state around makes // it easier to handle the recursion. class BulkTestSuiteMaker { /** * The class that defines simple and bulk tests methods. */ private Class startingClass; /** * List of ignored simple test names. */ private List ignored; /** * The TestSuite we're currently populating. Can change over time. */ private TestSuite result; /** * The prefix for simple test methods. Used to check if a test is in * the ignored list. */ private String prefix; /** * Constructor. * * @param startingClass the starting class */ public BulkTestSuiteMaker(Class startingClass) { this.startingClass = startingClass; } /** * Makes a hierarchal TestSuite based on the starting class. * * @return the hierarchal TestSuite for startingClass */ public TestSuite make() { this.result = new TestSuite(); this.prefix = getBaseName(startingClass); result.setName(prefix); BulkTest bulk = makeFirstTestCase(startingClass); ignored = new ArrayList(); String[] s = bulk.ignoredTests(); if (s != null) { ignored.addAll(Arrays.asList(s)); } make(bulk); return result; } /** * Appends all the simple tests and bulk tests defined by the given * instance's class to the current TestSuite. * * @param bulk An instance of the class that defines simple and bulk * tests for us to append */ void make(BulkTest bulk) { Class c = bulk.getClass(); Method[] all = c.getMethods(); for (int i = 0; i < all.length; i++) { if (isTest(all[i])) addTest(bulk, all[i]); if (isBulk(all[i])) addBulk(bulk, all[i]); } } /** * Adds the simple test defined by the given method to the TestSuite. * * @param bulk The instance of the class that defined the method * (I know it's weird. But the point is, we can clone the instance * and not have to worry about constructors.) * @param m The simple test method */ void addTest(BulkTest bulk, Method m) { BulkTest bulk2 = (BulkTest) bulk.clone(); bulk2.setName(m.getName()); bulk2.verboseName = prefix + "." + m.getName(); if (ignored.contains(bulk2.verboseName)) return; result.addTest(bulk2); } /** * Adds a whole new suite of tests that are defined by the result of * the given bulk test method. In other words, the given bulk test * method is invoked, and the resulting BulkTest instance is examined * for yet more simple and bulk tests. * * @param bulk The instance of the class that defined the method * @param m The bulk test method */ void addBulk(BulkTest bulk, Method m) { String verboseName = prefix + "." + m.getName(); if (ignored.contains(verboseName)) return; BulkTest bulk2; try { bulk2 = (BulkTest) m.invoke(bulk, null); if (bulk2 == null) return; } catch (InvocationTargetException ex) { ex.getTargetException().printStackTrace(); throw new Error(); // FIXME; } catch (IllegalAccessException ex) { ex.printStackTrace(); throw new Error(); // FIXME; } // Save current state on the stack. String oldPrefix = prefix; TestSuite oldResult = result; prefix = prefix + "." + m.getName(); result = new TestSuite(); result.setName(m.getName()); make(bulk2); oldResult.addTest(result); // Restore the old state prefix = oldPrefix; result = oldResult; } /** * Returns the base name of the given class. * * @param c the class * @return the name of that class, minus any package names */ private static String getBaseName(Class c) { String name = c.getName(); int p = name.lastIndexOf('.'); if (p > 0) { name = name.substring(p + 1); } return name; } // These three methods are used to create a valid BulkTest instance // from a class. private static Constructor getTestCaseConstructor(Class c) { try { return c.getConstructor(new Class[]{String.class}); } catch (NoSuchMethodException e) { throw new IllegalArgumentException(c + " must provide " + "a (String) constructor"); } } private static BulkTest makeTestCase(Class c, Method m) { Constructor con = getTestCaseConstructor(c); try { return (BulkTest) con.newInstance(new String[]{m.getName()}); } catch (InvocationTargetException e) { e.printStackTrace(); throw new RuntimeException(); // FIXME; } catch (IllegalAccessException e) { throw new Error(); // should never occur } catch (InstantiationException e) { throw new RuntimeException(); // FIXME; } } private static BulkTest makeFirstTestCase(Class c) { Method[] all = c.getMethods(); for (int i = 0; i < all.length; i++) { if (isTest(all[i])) return makeTestCase(c, all[i]); } throw new IllegalArgumentException(c.getName() + " must provide " + " at least one test method."); } /** * Returns true if the given method is a simple test method. */ private static boolean isTest(Method m) { if (!m.getName().startsWith("test")) return false; if (m.getReturnType() != Void.TYPE) return false; if (m.getParameterTypes().length != 0) return false; int mods = m.getModifiers(); if (Modifier.isStatic(mods)) return false; if (Modifier.isAbstract(mods)) return false; return true; } /** * Returns true if the given method is a bulk test method. */ private static boolean isBulk(Method m) { if (!m.getName().startsWith("bulkTest")) return false; if (m.getReturnType() != BulkTest.class) return false; if (m.getParameterTypes().length != 0) return false; int mods = m.getModifiers(); if (Modifier.isStatic(mods)) return false; if (Modifier.isAbstract(mods)) return false; return true; } } collections-generic-4.01/src/test/org/apache/commons/collections15/TestCollectionUtils.java0000644000175000017500000013014510464140760032336 0ustar giovannigiovanni/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.apache.commons.collections15.bag.HashBag; import org.apache.commons.collections15.buffer.BoundedFifoBuffer; import org.apache.commons.collections15.collection.*; import java.util.*; /** * Tests for CollectionUtils. * * @author Rodney Waldhoff * @author Matthew Hawthorne * @author Stephen Colebourne * @author Phil Steitz * @author Matt Hall, John Watkinson, Steven Melzer * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:39 $ */ public class TestCollectionUtils extends TestCase { public TestCollectionUtils(String testName) { super(testName); } public static Test suite() { return new TestSuite(TestCollectionUtils.class); } public static void main(String args[]) { String[] testCaseName = {TestCollectionUtils.class.getName()}; junit.textui.TestRunner.main(testCaseName); } private Collection collectionA = null; private Collection collectionB = null; public void setUp() { collectionA = new ArrayList(); collectionA.add("a"); collectionA.add("b"); collectionA.add("b"); collectionA.add("c"); collectionA.add("c"); collectionA.add("c"); collectionA.add("d"); collectionA.add("d"); collectionA.add("d"); collectionA.add("d"); collectionB = new LinkedList(); collectionB.add("e"); collectionB.add("d"); collectionB.add("d"); collectionB.add("c"); collectionB.add("c"); collectionB.add("c"); collectionB.add("b"); collectionB.add("b"); collectionB.add("b"); collectionB.add("b"); } public void testGetCardinalityMap() { Map freq = CollectionUtils.getCardinalityMap(collectionA); assertEquals(new Integer(1), freq.get("a")); assertEquals(new Integer(2), freq.get("b")); assertEquals(new Integer(3), freq.get("c")); assertEquals(new Integer(4), freq.get("d")); assertNull(freq.get("e")); freq = CollectionUtils.getCardinalityMap(collectionB); assertNull(freq.get("a")); assertEquals(new Integer(4), freq.get("b")); assertEquals(new Integer(3), freq.get("c")); assertEquals(new Integer(2), freq.get("d")); assertEquals(new Integer(1), freq.get("e")); } public void testCardinality() { assertEquals(1, CollectionUtils.cardinality("a", collectionA)); assertEquals(2, CollectionUtils.cardinality("b", collectionA)); assertEquals(3, CollectionUtils.cardinality("c", collectionA)); assertEquals(4, CollectionUtils.cardinality("d", collectionA)); assertEquals(0, CollectionUtils.cardinality("e", collectionA)); assertEquals(0, CollectionUtils.cardinality("a", collectionB)); assertEquals(4, CollectionUtils.cardinality("b", collectionB)); assertEquals(3, CollectionUtils.cardinality("c", collectionB)); assertEquals(2, CollectionUtils.cardinality("d", collectionB)); assertEquals(1, CollectionUtils.cardinality("e", collectionB)); List numberList = new ArrayList(); numberList.add(new Long(1)); numberList.add(new Integer(1)); assertEquals(1, CollectionUtils.cardinality(new Long(1), numberList)); assertEquals(1, CollectionUtils.cardinality(new Integer(1), numberList)); Set set = new HashSet(); set.add("A"); set.add("C"); set.add("E"); set.add("E"); assertEquals(1, CollectionUtils.cardinality("A", set)); assertEquals(0, CollectionUtils.cardinality("B", set)); assertEquals(1, CollectionUtils.cardinality("C", set)); assertEquals(0, CollectionUtils.cardinality("D", set)); assertEquals(1, CollectionUtils.cardinality("E", set)); Bag bag = new HashBag(); bag.add("A", 3); bag.add("C"); bag.add("E"); bag.add("E"); assertEquals(3, CollectionUtils.cardinality("A", bag)); assertEquals(0, CollectionUtils.cardinality("B", bag)); assertEquals(1, CollectionUtils.cardinality("C", bag)); assertEquals(0, CollectionUtils.cardinality("D", bag)); assertEquals(2, CollectionUtils.cardinality("E", bag)); } public void testCardinalityOfNull() { List list = new ArrayList(); assertEquals(0, CollectionUtils.cardinality(null, list)); { Map freq = CollectionUtils.getCardinalityMap(list); assertNull(freq.get(null)); } list.add("A"); assertEquals(0, CollectionUtils.cardinality(null, list)); { Map freq = CollectionUtils.getCardinalityMap(list); assertNull(freq.get(null)); } list.add(null); assertEquals(1, CollectionUtils.cardinality(null, list)); { Map freq = CollectionUtils.getCardinalityMap(list); assertEquals(new Integer(1), freq.get(null)); } list.add("B"); assertEquals(1, CollectionUtils.cardinality(null, list)); { Map freq = CollectionUtils.getCardinalityMap(list); assertEquals(new Integer(1), freq.get(null)); } list.add(null); assertEquals(2, CollectionUtils.cardinality(null, list)); { Map freq = CollectionUtils.getCardinalityMap(list); assertEquals(new Integer(2), freq.get(null)); } list.add("B"); assertEquals(2, CollectionUtils.cardinality(null, list)); { Map freq = CollectionUtils.getCardinalityMap(list); assertEquals(new Integer(2), freq.get(null)); } list.add(null); assertEquals(3, CollectionUtils.cardinality(null, list)); { Map freq = CollectionUtils.getCardinalityMap(list); assertEquals(new Integer(3), freq.get(null)); } } public void testContainsAny() { Collection empty = new ArrayList(0); Collection one = new ArrayList(1); one.add("1"); Collection two = new ArrayList(1); two.add("2"); Collection three = new ArrayList(1); three.add("3"); Collection odds = new ArrayList(2); odds.add("1"); odds.add("3"); assertTrue("containsAny({1},{1,3}) should return true.", CollectionUtils.containsAny(one, odds)); assertTrue("containsAny({1,3},{1}) should return true.", CollectionUtils.containsAny(odds, one)); assertTrue("containsAny({3},{1,3}) should return true.", CollectionUtils.containsAny(three, odds)); assertTrue("containsAny({1,3},{3}) should return true.", CollectionUtils.containsAny(odds, three)); assertTrue("containsAny({2},{2}) should return true.", CollectionUtils.containsAny(two, two)); assertTrue("containsAny({1,3},{1,3}) should return true.", CollectionUtils.containsAny(odds, odds)); assertTrue("containsAny({2},{1,3}) should return false.", !CollectionUtils.containsAny(two, odds)); assertTrue("containsAny({1,3},{2}) should return false.", !CollectionUtils.containsAny(odds, two)); assertTrue("containsAny({1},{3}) should return false.", !CollectionUtils.containsAny(one, three)); assertTrue("containsAny({3},{1}) should return false.", !CollectionUtils.containsAny(three, one)); assertTrue("containsAny({1,3},{}) should return false.", !CollectionUtils.containsAny(odds, empty)); assertTrue("containsAny({},{1,3}) should return false.", !CollectionUtils.containsAny(empty, odds)); assertTrue("containsAny({},{}) should return false.", !CollectionUtils.containsAny(empty, empty)); } public void testUnion() { Collection col = CollectionUtils.union(collectionA, collectionB); Map freq = CollectionUtils.getCardinalityMap(col); assertEquals(new Integer(1), freq.get("a")); assertEquals(new Integer(4), freq.get("b")); assertEquals(new Integer(3), freq.get("c")); assertEquals(new Integer(4), freq.get("d")); assertEquals(new Integer(1), freq.get("e")); Collection col2 = CollectionUtils.union(collectionB, collectionA); Map freq2 = CollectionUtils.getCardinalityMap(col2); assertEquals(new Integer(1), freq2.get("a")); assertEquals(new Integer(4), freq2.get("b")); assertEquals(new Integer(3), freq2.get("c")); assertEquals(new Integer(4), freq2.get("d")); assertEquals(new Integer(1), freq2.get("e")); } public void testIntersection() { Collection col = CollectionUtils.intersection(collectionA, collectionB); Map freq = CollectionUtils.getCardinalityMap(col); assertNull(freq.get("a")); assertEquals(new Integer(2), freq.get("b")); assertEquals(new Integer(3), freq.get("c")); assertEquals(new Integer(2), freq.get("d")); assertNull(freq.get("e")); Collection col2 = CollectionUtils.intersection(collectionB, collectionA); Map freq2 = CollectionUtils.getCardinalityMap(col2); assertNull(freq2.get("a")); assertEquals(new Integer(2), freq2.get("b")); assertEquals(new Integer(3), freq2.get("c")); assertEquals(new Integer(2), freq2.get("d")); assertNull(freq2.get("e")); } public void testDisjunction() { Collection col = CollectionUtils.disjunction(collectionA, collectionB); Map freq = CollectionUtils.getCardinalityMap(col); assertEquals(new Integer(1), freq.get("a")); assertEquals(new Integer(2), freq.get("b")); assertNull(freq.get("c")); assertEquals(new Integer(2), freq.get("d")); assertEquals(new Integer(1), freq.get("e")); Collection col2 = CollectionUtils.disjunction(collectionB, collectionA); Map freq2 = CollectionUtils.getCardinalityMap(col2); assertEquals(new Integer(1), freq2.get("a")); assertEquals(new Integer(2), freq2.get("b")); assertNull(freq2.get("c")); assertEquals(new Integer(2), freq2.get("d")); assertEquals(new Integer(1), freq2.get("e")); } public void testDisjunctionAsUnionMinusIntersection() { Collection dis = CollectionUtils.disjunction(collectionA, collectionB); Collection un = CollectionUtils.union(collectionA, collectionB); Collection inter = CollectionUtils.intersection(collectionA, collectionB); assertTrue(CollectionUtils.isEqualCollection(dis, CollectionUtils.subtract(un, inter))); } public void testDisjunctionAsSymmetricDifference() { Collection dis = CollectionUtils.disjunction(collectionA, collectionB); Collection amb = CollectionUtils.subtract(collectionA, collectionB); Collection bma = CollectionUtils.subtract(collectionB, collectionA); assertTrue(CollectionUtils.isEqualCollection(dis, CollectionUtils.union(amb, bma))); } public void testSubtract() { Collection col = CollectionUtils.subtract(collectionA, collectionB); Map freq = CollectionUtils.getCardinalityMap(col); assertEquals(new Integer(1), freq.get("a")); assertNull(freq.get("b")); assertNull(freq.get("c")); assertEquals(new Integer(2), freq.get("d")); assertNull(freq.get("e")); Collection col2 = CollectionUtils.subtract(collectionB, collectionA); Map freq2 = CollectionUtils.getCardinalityMap(col2); assertEquals(new Integer(1), freq2.get("e")); assertNull(freq2.get("d")); assertNull(freq2.get("c")); assertEquals(new Integer(2), freq2.get("b")); assertNull(freq2.get("a")); } public void testIsSubCollectionOfSelf() { assertTrue(CollectionUtils.isSubCollection(collectionA, collectionA)); assertTrue(CollectionUtils.isSubCollection(collectionB, collectionB)); } public void testIsSubCollection() { assertTrue(!CollectionUtils.isSubCollection(collectionA, collectionB)); assertTrue(!CollectionUtils.isSubCollection(collectionB, collectionA)); } public void testIsSubCollection2() { Collection c = new ArrayList(); assertTrue(CollectionUtils.isSubCollection(c, collectionA)); assertTrue(!CollectionUtils.isSubCollection(collectionA, c)); c.add("a"); assertTrue(CollectionUtils.isSubCollection(c, collectionA)); assertTrue(!CollectionUtils.isSubCollection(collectionA, c)); c.add("b"); assertTrue(CollectionUtils.isSubCollection(c, collectionA)); assertTrue(!CollectionUtils.isSubCollection(collectionA, c)); c.add("b"); assertTrue(CollectionUtils.isSubCollection(c, collectionA)); assertTrue(!CollectionUtils.isSubCollection(collectionA, c)); c.add("c"); assertTrue(CollectionUtils.isSubCollection(c, collectionA)); assertTrue(!CollectionUtils.isSubCollection(collectionA, c)); c.add("c"); assertTrue(CollectionUtils.isSubCollection(c, collectionA)); assertTrue(!CollectionUtils.isSubCollection(collectionA, c)); c.add("c"); assertTrue(CollectionUtils.isSubCollection(c, collectionA)); assertTrue(!CollectionUtils.isSubCollection(collectionA, c)); c.add("d"); assertTrue(CollectionUtils.isSubCollection(c, collectionA)); assertTrue(!CollectionUtils.isSubCollection(collectionA, c)); c.add("d"); assertTrue(CollectionUtils.isSubCollection(c, collectionA)); assertTrue(!CollectionUtils.isSubCollection(collectionA, c)); c.add("d"); assertTrue(CollectionUtils.isSubCollection(c, collectionA)); assertTrue(!CollectionUtils.isSubCollection(collectionA, c)); c.add("d"); assertTrue(CollectionUtils.isSubCollection(c, collectionA)); assertTrue(CollectionUtils.isSubCollection(collectionA, c)); c.add("e"); assertTrue(!CollectionUtils.isSubCollection(c, collectionA)); assertTrue(CollectionUtils.isSubCollection(collectionA, c)); } public void testIsEqualCollectionToSelf() { assertTrue(CollectionUtils.isEqualCollection(collectionA, collectionA)); assertTrue(CollectionUtils.isEqualCollection(collectionB, collectionB)); } public void testIsEqualCollection() { assertTrue(!CollectionUtils.isEqualCollection(collectionA, collectionB)); assertTrue(!CollectionUtils.isEqualCollection(collectionB, collectionA)); } public void testIsEqualCollection2() { Collection a = new ArrayList(); Collection b = new ArrayList(); assertTrue(CollectionUtils.isEqualCollection(a, b)); assertTrue(CollectionUtils.isEqualCollection(b, a)); a.add("1"); assertTrue(!CollectionUtils.isEqualCollection(a, b)); assertTrue(!CollectionUtils.isEqualCollection(b, a)); b.add("1"); assertTrue(CollectionUtils.isEqualCollection(a, b)); assertTrue(CollectionUtils.isEqualCollection(b, a)); a.add("2"); assertTrue(!CollectionUtils.isEqualCollection(a, b)); assertTrue(!CollectionUtils.isEqualCollection(b, a)); b.add("2"); assertTrue(CollectionUtils.isEqualCollection(a, b)); assertTrue(CollectionUtils.isEqualCollection(b, a)); a.add("1"); assertTrue(!CollectionUtils.isEqualCollection(a, b)); assertTrue(!CollectionUtils.isEqualCollection(b, a)); b.add("1"); assertTrue(CollectionUtils.isEqualCollection(a, b)); assertTrue(CollectionUtils.isEqualCollection(b, a)); } public void testIsProperSubCollection() { Collection a = new ArrayList(); Collection b = new ArrayList(); assertTrue(!CollectionUtils.isProperSubCollection(a, b)); b.add("1"); assertTrue(CollectionUtils.isProperSubCollection(a, b)); assertTrue(!CollectionUtils.isProperSubCollection(b, a)); assertTrue(!CollectionUtils.isProperSubCollection(b, b)); assertTrue(!CollectionUtils.isProperSubCollection(a, a)); a.add("1"); a.add("2"); b.add("2"); assertTrue(!CollectionUtils.isProperSubCollection(b, a)); assertTrue(!CollectionUtils.isProperSubCollection(a, b)); a.add("1"); assertTrue(CollectionUtils.isProperSubCollection(b, a)); assertTrue(CollectionUtils.isProperSubCollection(CollectionUtils.intersection(collectionA, collectionB), collectionA)); assertTrue(CollectionUtils.isProperSubCollection(CollectionUtils.subtract(a, b), a)); assertTrue(!CollectionUtils.isProperSubCollection(a, CollectionUtils.subtract(a, b))); } public void testFind() { Predicate testPredicate = PredicateUtils.equalPredicate("d"); Object test = CollectionUtils.find(collectionA, testPredicate); assertTrue(test.equals("d")); testPredicate = PredicateUtils.equalPredicate("de"); test = CollectionUtils.find(collectionA, testPredicate); assertTrue(test == null); assertEquals(CollectionUtils.find(null, testPredicate), null); assertEquals(CollectionUtils.find(collectionA, null), null); } public void testForAllDo() { Closure testClosure = ClosureUtils.invokerClosure("clear"); Collection col = new ArrayList(); col.add(collectionA); col.add(collectionB); CollectionUtils.forAllDo(col, testClosure); assertTrue(collectionA.isEmpty() && collectionB.isEmpty()); CollectionUtils.forAllDo(col, null); assertTrue(collectionA.isEmpty() && collectionB.isEmpty()); CollectionUtils.forAllDo(null, testClosure); col.add(null); // null should be OK CollectionUtils.forAllDo(col, testClosure); col.add("x"); // This will lead to FunctorException try { CollectionUtils.forAllDo(col, testClosure); fail("Expecting FunctorException"); } catch (FunctorException ex) { // expected from invoker -- method not found } } public void testIndex() { // normal map behavior when index is an Integer and a key Map map = new HashMap(); map.put(new Integer(0), "zero"); map.put(new Integer(-1), "minusOne"); Object test = CollectionUtils.index(map, 0); assertTrue(test.equals("zero")); test = CollectionUtils.index(map, new Integer(-1)); assertTrue(test.equals("minusOne")); // map, non-integer key that does not exist -- map returned test = CollectionUtils.index(map, "missing"); assertTrue(test.equals(map)); // map, integer not a key, valid index -- "some" element of keyset returned test = CollectionUtils.index(map, new Integer(1)); assertTrue(map.keySet().contains(test)); // map, integer not a key, not valid index -- "dead" keyset iterator returned test = CollectionUtils.index(map, new Integer(4)); assertTrue((test instanceof Iterator) && !((Iterator) test).hasNext()); // sorted map, integer not a key, valid index -- ith key returned SortedMap map2 = new TreeMap(); map2.put(new Integer(23), "u"); map2.put(new Integer(21), "x"); map2.put(new Integer(17), "v"); map2.put(new Integer(42), "w"); Integer val = (Integer) CollectionUtils.index(map2, 0); assertTrue(val.intValue() == 17); val = (Integer) CollectionUtils.index(map2, 1); assertTrue(val.intValue() == 21); val = (Integer) CollectionUtils.index(map2, 2); assertTrue(val.intValue() == 23); val = (Integer) CollectionUtils.index(map2, 3); assertTrue(val.intValue() == 42); // list, entry exists List list = new ArrayList(); list.add("zero"); list.add("one"); test = CollectionUtils.index(list, 0); assertTrue(test.equals("zero")); test = CollectionUtils.index(list, 1); assertTrue(test.equals("one")); // list, non-existent entry -- IndexOutOfBoundsException try { test = CollectionUtils.index(list, 2); fail("Expecting IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { // expected } // iterator, entry exists Iterator iterator = list.iterator(); test = CollectionUtils.index(iterator, 0); assertTrue(test.equals("zero")); iterator = list.iterator(); test = CollectionUtils.index(iterator, 1); assertTrue(test.equals("one")); // iterator, non-existent entry -- "dead" iterator returned test = CollectionUtils.index(iterator, 3); assertTrue(test.equals(iterator) && !iterator.hasNext()); // Enumeration, entry exists Vector vector = new Vector(list); Enumeration enumeration = vector.elements(); test = CollectionUtils.index(enumeration, 0); assertTrue(test.equals("zero")); enumeration = vector.elements(); test = CollectionUtils.index(enumeration, 1); assertTrue(test.equals("one")); // Enumeration, non-existent entry -- "dead" enumerator returned test = CollectionUtils.index(enumeration, 3); assertTrue(test.equals(enumeration) && !enumeration.hasMoreElements()); // Collection, entry exists Bag bag = new HashBag(); bag.add("element", 1); test = CollectionUtils.index(bag, 0); assertTrue(test.equals("element")); // Collection, non-existent entry -- "dead" iterator returned test = CollectionUtils.index(bag, 2); assertTrue((test instanceof Iterator) && !((Iterator) test).hasNext()); // Object array, entry exists Object[] objArray = new Object[2]; objArray[0] = "zero"; objArray[1] = "one"; test = CollectionUtils.index(objArray, 0); assertTrue(test.equals("zero")); test = CollectionUtils.index(objArray, 1); assertTrue(test.equals("one")); // Object array, non-existent entry -- ArrayIndexOutOfBoundsException try { test = CollectionUtils.index(objArray, 2); fail("Expecting ArrayIndexOutOfBoundsException."); } catch (ArrayIndexOutOfBoundsException ex) { // expected } // Non-collection object -- returned unchanged Object obj = new Object(); test = CollectionUtils.index(obj, obj); assertTrue(test.equals(obj)); } public void testGet() { { // Unordered map, entries exist Map expected = new HashMap(); expected.put("zeroKey", "zero"); expected.put("oneKey", "one"); Map found = new HashMap(); Map.Entry entry = (Map.Entry) (CollectionUtils.get(expected, 0)); found.put(entry.getKey(), entry.getValue()); entry = (Map.Entry) (CollectionUtils.get(expected, 1)); found.put(entry.getKey(), entry.getValue()); assertEquals(expected, found); // Map index out of range try { CollectionUtils.get(expected, 2); fail("Expecting IndexOutOfBoundsException."); } catch (IndexOutOfBoundsException e) { // expected } try { CollectionUtils.get(expected, -2); fail("Expecting IndexOutOfBoundsException."); } catch (IndexOutOfBoundsException e) { // expected } } { // Sorted map, entries exist, should respect order SortedMap map = new TreeMap(); map.put("zeroKey", "zero"); map.put("oneKey", "one"); Object test = CollectionUtils.get(map, 1); assertEquals("zeroKey", ((Map.Entry) test).getKey()); assertEquals("zero", ((Map.Entry) test).getValue()); test = CollectionUtils.get(map, 0); assertEquals("oneKey", ((Map.Entry) test).getKey()); assertEquals("one", ((Map.Entry) test).getValue()); } { // List, entry exists List list = new ArrayList(); list.add("zero"); list.add("one"); assertEquals("zero", CollectionUtils.get(list, 0)); assertEquals("one", CollectionUtils.get(list, 1)); // list, non-existent entry -- IndexOutOfBoundsException try { CollectionUtils.get(list, 2); fail("Expecting IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { // expected } // Iterator, entry exists Iterator iterator = list.iterator(); assertEquals("zero", CollectionUtils.get(iterator, 0)); iterator = list.iterator(); assertEquals("one", CollectionUtils.get(iterator, 1)); // Iterator, non-existent entry try { CollectionUtils.get(iterator, 3); fail("Expecting IndexOutOfBoundsException."); } catch (IndexOutOfBoundsException e) { // expected } assertTrue(!iterator.hasNext()); } { // Enumeration, entry exists Vector vector = new Vector(); vector.addElement("zero"); vector.addElement("one"); Enumeration enumeration = vector.elements(); assertEquals("zero", CollectionUtils.get(enumeration, 0)); enumeration = vector.elements(); assertEquals("one", CollectionUtils.get(enumeration, 1)); // Enumerator, non-existent entry try { CollectionUtils.get(enumeration, 3); fail("Expecting IndexOutOfBoundsException."); } catch (IndexOutOfBoundsException e) { // expected } assertTrue(!enumeration.hasMoreElements()); } { // Collection, entry exists Bag bag = new HashBag(); bag.add("element", 1); assertEquals("element", CollectionUtils.get(bag, 0)); // Collection, non-existent entry try { CollectionUtils.get(bag, 1); fail("Expceting IndexOutOfBoundsException."); } catch (IndexOutOfBoundsException e) { // expected } } { // Object array, entry exists Object[] objArray = new Object[2]; objArray[0] = "zero"; objArray[1] = "one"; assertEquals("zero", CollectionUtils.get(objArray, 0)); assertEquals("one", CollectionUtils.get(objArray, 1)); // Object array, non-existent entry -- ArrayIndexOutOfBoundsException try { CollectionUtils.get(objArray, 2); fail("Expecting IndexOutOfBoundsException."); } catch (IndexOutOfBoundsException ex) { // expected } } { // Primitive array, entry exists int[] array = new int[2]; array[0] = 10; array[1] = 20; assertEquals(new Integer(10), CollectionUtils.get(array, 0)); assertEquals(new Integer(20), CollectionUtils.get(array, 1)); // Object array, non-existent entry -- ArrayIndexOutOfBoundsException try { CollectionUtils.get(array, 2); fail("Expecting IndexOutOfBoundsException."); } catch (IndexOutOfBoundsException ex) { // expected } } { // Invalid object Object obj = new Object(); try { CollectionUtils.get(obj, 0); fail("Expecting IllegalArgumentException."); } catch (IllegalArgumentException e) { // expected } try { CollectionUtils.get(null, 0); fail("Expecting IllegalArgumentException."); } catch (IllegalArgumentException e) { // expected } } } public void testSize_List() { List list = new ArrayList(); assertEquals(0, CollectionUtils.size(list)); list.add("a"); assertEquals(1, CollectionUtils.size(list)); list.add("b"); assertEquals(2, CollectionUtils.size(list)); } public void testSize_Map() { Map map = new HashMap(); assertEquals(0, CollectionUtils.size(map)); map.put("1", "a"); assertEquals(1, CollectionUtils.size(map)); map.put("2", "b"); assertEquals(2, CollectionUtils.size(map)); } public void testSize_Array() { Object[] objectArray = new Object[0]; assertEquals(0, CollectionUtils.size(objectArray)); String[] stringArray = new String[3]; assertEquals(3, CollectionUtils.size(stringArray)); stringArray[0] = "a"; stringArray[1] = "b"; stringArray[2] = "c"; assertEquals(3, CollectionUtils.size(stringArray)); } public void testSize_PrimitiveArray() { int[] intArray = new int[0]; assertEquals(0, CollectionUtils.size(intArray)); double[] doubleArray = new double[3]; assertEquals(3, CollectionUtils.size(doubleArray)); doubleArray[0] = 0.0d; doubleArray[1] = 1.0d; doubleArray[2] = 2.5d; assertEquals(3, CollectionUtils.size(doubleArray)); } public void testSize_Enumeration() { Vector list = new Vector(); assertEquals(0, CollectionUtils.size(list.elements())); list.add("a"); assertEquals(1, CollectionUtils.size(list.elements())); list.add("b"); assertEquals(2, CollectionUtils.size(list.elements())); } public void testSize_Iterator() { List list = new ArrayList(); assertEquals(0, CollectionUtils.size(list.iterator())); list.add("a"); assertEquals(1, CollectionUtils.size(list.iterator())); list.add("b"); assertEquals(2, CollectionUtils.size(list.iterator())); } public void testSize_Other() { try { CollectionUtils.size(null); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException e) { } try { CollectionUtils.size("not a list"); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException e) { } } //----------------------------------------------------------------------- private static Predicate EQUALS_TWO = new Predicate() { public boolean evaluate(String input) { return (input.equals("Two")); } }; public void testFilter() { List list = new ArrayList(); list.add("One"); list.add("Two"); list.add("Three"); list.add("Four"); CollectionUtils.filter(list, EQUALS_TWO); assertEquals(1, list.size()); assertEquals("Two", list.get(0)); list = new ArrayList(); list.add("One"); list.add("Two"); list.add("Three"); list.add("Four"); CollectionUtils.filter(list, null); assertEquals(4, list.size()); CollectionUtils.filter(null, EQUALS_TWO); assertEquals(4, list.size()); CollectionUtils.filter(null, null); assertEquals(4, list.size()); } public void testCountMatches() { List list = new ArrayList(); list.add("One"); list.add("Two"); list.add("Three"); list.add("Four"); int count = CollectionUtils.countMatches(list, EQUALS_TWO); assertEquals(4, list.size()); assertEquals(1, count); assertEquals(0, CollectionUtils.countMatches(list, null)); assertEquals(0, CollectionUtils.countMatches(null, EQUALS_TWO)); assertEquals(0, CollectionUtils.countMatches(null, null)); } public void testExists() { List list = new ArrayList(); assertEquals(false, CollectionUtils.exists(null, null)); assertEquals(false, CollectionUtils.exists(list, null)); assertEquals(false, CollectionUtils.exists(null, EQUALS_TWO)); assertEquals(false, CollectionUtils.exists(list, EQUALS_TWO)); list.add("One"); list.add("Three"); list.add("Four"); assertEquals(false, CollectionUtils.exists(list, EQUALS_TWO)); list.add("Two"); assertEquals(true, CollectionUtils.exists(list, EQUALS_TWO)); } public void testSelect() { List list = new ArrayList(); list.add("One"); list.add("Two"); list.add("Three"); list.add("Four"); Collection output = CollectionUtils.select(list, EQUALS_TWO); assertEquals(4, list.size()); assertEquals(1, output.size()); assertEquals("Two", output.iterator().next()); } public void testSelectRejected() { List list = new ArrayList(); list.add("One"); list.add("Two"); list.add("Three"); list.add("Four"); Collection output = CollectionUtils.selectRejected(list, EQUALS_TWO); assertEquals(4, list.size()); assertEquals(3, output.size()); assertTrue(output.contains("One")); assertTrue(output.contains("Three")); assertTrue(output.contains("Four")); } public void testCollect() { Transformer transformer = TransformerUtils.constantTransformer("z"); Collection collection = CollectionUtils.collect(collectionA, transformer); assertTrue(collection.size() == collectionA.size()); assertTrue(collectionA.contains("a") && !collectionA.contains("z")); assertTrue(collection.contains("z") && !collection.contains("a")); collection = new ArrayList(); CollectionUtils.collect(collectionA, transformer, collection); assertTrue(collection.size() == collectionA.size()); assertTrue(collectionA.contains("a") && !collectionA.contains("z")); assertTrue(collection.contains("z") && !collection.contains("a")); Iterator iterator = null; collection = new ArrayList(); CollectionUtils.collect(iterator, transformer, collection); iterator = collectionA.iterator(); CollectionUtils.collect(iterator, transformer, collection); assertTrue(collection.size() == collectionA.size()); assertTrue(collectionA.contains("a") && !collectionA.contains("z")); assertTrue(collection.contains("z") && !collection.contains("a")); iterator = collectionA.iterator(); collection = CollectionUtils.collect(iterator, transformer); assertTrue(collection.size() == collectionA.size()); assertTrue(collection.contains("z") && !collection.contains("a")); collection = CollectionUtils.collect((Iterator) null, (Transformer) null); assertTrue(collection.size() == 0); int size = collectionA.size(); CollectionUtils.collect((Collection) null, transformer, collectionA); assertTrue(collectionA.size() == size && collectionA.contains("a")); // null transformer is no longer allowed // CollectionUtils.collect(collectionB, null, collectionA); // assertTrue(collectionA.size() == size && collectionA.contains("a")); } Transformer TRANSFORM_TO_INTEGER = new Transformer() { public Object transform(Object input) { return new Integer((String) input); } }; public void testTransform1() { List list = new ArrayList(); list.add("1"); list.add("2"); list.add("3"); CollectionUtils.transform(list, TRANSFORM_TO_INTEGER); assertEquals(3, list.size()); assertEquals(new Integer(1), list.get(0)); assertEquals(new Integer(2), list.get(1)); assertEquals(new Integer(3), list.get(2)); list = new ArrayList(); list.add("1"); list.add("2"); list.add("3"); CollectionUtils.transform(null, TRANSFORM_TO_INTEGER); assertEquals(3, list.size()); CollectionUtils.transform(list, null); assertEquals(3, list.size()); CollectionUtils.transform(null, null); assertEquals(3, list.size()); } public void testTransform2() { Set set = new HashSet(); set.add("1"); set.add("2"); set.add("3"); CollectionUtils.transform(set, new Transformer() { public Object transform(Object input) { return new Integer(4); } }); assertEquals(1, set.size()); assertEquals(new Integer(4), set.iterator().next()); } public void testPredicatedCollection() { Predicate predicate = new Predicate() { public boolean evaluate(Object o) { return o instanceof String; } }; Collection collection = CollectionUtils.predicatedCollection(new ArrayList(), predicate); assertTrue("returned object should be a PredicatedCollection", collection instanceof PredicatedCollection); try { collection = CollectionUtils.predicatedCollection(new ArrayList(), null); fail("Expecting IllegalArgumentException for null predicate."); } catch (IllegalArgumentException ex) { // expected } try { collection = CollectionUtils.predicatedCollection(null, predicate); fail("Expecting IllegalArgumentException for null collection."); } catch (IllegalArgumentException ex) { // expected } } public BulkTest bulkTestTypedCollection() { return new TestTypedCollection("") { public Collection typedCollection() { return CollectionUtils.typedCollection(new ArrayList(), super.getType()); } public BulkTest bulkTestAll() { return new AbstractTestCollection("") { public Collection makeCollection() { return typedCollection(); } public Collection makeConfirmedCollection() { return new ArrayList(); } public Collection makeConfirmedFullCollection() { ArrayList list = new ArrayList(); list.addAll(java.util.Arrays.asList(getFullElements())); return list; } public Object[] getFullElements() { return getFullNonNullStringElements(); } public Object[] getOtherElements() { return getOtherNonNullStringElements(); } }; } }; } public void testIsFull() { Set set = new HashSet(); set.add("1"); set.add("2"); set.add("3"); try { CollectionUtils.isFull(null); fail(); } catch (NullPointerException ex) { } assertEquals(false, CollectionUtils.isFull(set)); BoundedFifoBuffer buf = new BoundedFifoBuffer(set); assertEquals(true, CollectionUtils.isFull(buf)); buf.remove("2"); assertEquals(false, CollectionUtils.isFull(buf)); buf.add("2"); assertEquals(true, CollectionUtils.isFull(buf)); Buffer buf2 = BufferUtils.synchronizedBuffer(buf); assertEquals(true, CollectionUtils.isFull(buf2)); buf2.remove("2"); assertEquals(false, CollectionUtils.isFull(buf2)); buf2.add("2"); assertEquals(true, CollectionUtils.isFull(buf2)); } public void testMaxSize() { Set set = new HashSet(); set.add("1"); set.add("2"); set.add("3"); try { CollectionUtils.maxSize(null); fail(); } catch (NullPointerException ex) { } assertEquals(-1, CollectionUtils.maxSize(set)); BoundedFifoBuffer buf = new BoundedFifoBuffer(set); assertEquals(3, CollectionUtils.maxSize(buf)); buf.remove("2"); assertEquals(3, CollectionUtils.maxSize(buf)); buf.add("2"); assertEquals(3, CollectionUtils.maxSize(buf)); Buffer buf2 = BufferUtils.synchronizedBuffer(buf); assertEquals(3, CollectionUtils.maxSize(buf2)); buf2.remove("2"); assertEquals(3, CollectionUtils.maxSize(buf2)); buf2.add("2"); assertEquals(3, CollectionUtils.maxSize(buf2)); } public void testIntersectionUsesMethodEquals() { // Let elta and eltb be objects... Object elta = new Integer(17); Object eltb = new Integer(17); // ...which are equal... assertEquals(elta, eltb); assertEquals(eltb, elta); // ...but not the same (==). assertTrue(elta != eltb); // Let cola and colb be collections15... Collection cola = new ArrayList(); Collection colb = new ArrayList(); // ...which contain elta and eltb, // respectively. cola.add(elta); colb.add(eltb); // Then the intersection of the two // should contain one element. Collection intersection = CollectionUtils.intersection(cola, colb); assertEquals(1, intersection.size()); // In practice, this element will be the same (==) as elta // or eltb, although this isn't strictly part of the // contract. Object eltc = intersection.iterator().next(); assertTrue((eltc == elta && eltc != eltb) || (eltc != elta && eltc == eltb)); // In any event, this element remains equal, // to both elta and eltb. assertEquals(elta, eltc); assertEquals(eltc, elta); assertEquals(eltb, eltc); assertEquals(eltc, eltb); } public void testTransformedCollection() { Transformer transformer = TransformerUtils.nopTransformer(); Collection collection = CollectionUtils.transformedCollection(new ArrayList(), transformer); assertTrue("returned object should be a TransformedCollection", collection instanceof TransformedCollection); try { collection = CollectionUtils.transformedCollection(new ArrayList(), null); fail("Expecting IllegalArgumentException for null transformer."); } catch (IllegalArgumentException ex) { // expected } try { collection = CollectionUtils.transformedCollection(null, transformer); fail("Expecting IllegalArgumentException for null collection."); } catch (IllegalArgumentException ex) { // expected } } public void testSynchronizedCollection() { Collection col = CollectionUtils.synchronizedCollection(new ArrayList()); assertTrue("Returned object should be a SynchronizedCollection.", col instanceof SynchronizedCollection); try { col = CollectionUtils.synchronizedCollection(null); fail("Expecting IllegalArgumentException for null collection."); } catch (IllegalArgumentException ex) { // expected } } public void testUnmodifiableCollection() { Collection col = CollectionUtils.unmodifiableCollection(new ArrayList()); assertTrue("Returned object should be a UnmodifiableCollection.", col instanceof UnmodifiableCollection); try { col = CollectionUtils.unmodifiableCollection(null); fail("Expecting IllegalArgumentException for null collection."); } catch (IllegalArgumentException ex) { // expected } } } collections-generic-4.01/src/test/org/apache/commons/collections15/iterators/0000755000175000017500000000000011664401370027527 5ustar giovannigiovannicollections-generic-4.01/src/test/org/apache/commons/collections15/iterators/TestIteratorChain.java0000644000175000017500000001111410464140764033770 0ustar giovannigiovanni/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.iterators; import junit.framework.Test; import junit.framework.TestSuite; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; /** * Tests the IteratorChain class. * * @author James Strachan * @author Mauricio S. Moura * @author Matt Hall, John Watkinson, Morgan Delagrange * @version $Revision: 1.1 $ $Date: 2005/10/11 19:11:58 $ */ public class TestIteratorChain extends AbstractTestIterator { protected String[] testArray = {"One", "Two", "Three", "Four", "Five", "Six"}; protected List list1 = null; protected List list2 = null; protected List list3 = null; public static Test suite() { return new TestSuite(TestIteratorChain.class); } public TestIteratorChain(String testName) { super(testName); } public void setUp() { list1 = new ArrayList(); list1.add("One"); list1.add("Two"); list1.add("Three"); list2 = new ArrayList(); list2.add("Four"); list3 = new ArrayList(); list3.add("Five"); list3.add("Six"); } public Iterator makeEmptyIterator() { ArrayList list = new ArrayList(); return new IteratorChain(list.iterator()); } public Iterator makeFullIterator() { IteratorChain chain = new IteratorChain(); chain.addIterator(list1.iterator()); chain.addIterator(list2.iterator()); chain.addIterator(list3.iterator()); return chain; } public void testIterator() { Iterator iter = (Iterator) makeFullIterator(); for (int i = 0; i < testArray.length; i++) { Object testValue = testArray[i]; Object iterValue = iter.next(); assertEquals("Iteration value is correct", testValue, iterValue); } assertTrue("Iterator should now be empty", !iter.hasNext()); try { Object testValue = iter.next(); } catch (Exception e) { assertTrue("NoSuchElementException must be thrown", e.getClass().equals((new NoSuchElementException()).getClass())); } } public void testRemove() { Iterator iter = (Iterator) makeFullIterator(); try { iter.remove(); fail("Calling remove before the first call to next() should throw an exception"); } catch (IllegalStateException e) { } for (int i = 0; i < testArray.length; i++) { Object testValue = testArray[i]; Object iterValue = iter.next(); assertEquals("Iteration value is correct", testValue, iterValue); if (!iterValue.equals("Four")) { iter.remove(); } } assertTrue("List is empty", list1.size() == 0); assertTrue("List is empty", list2.size() == 1); assertTrue("List is empty", list3.size() == 0); } public void testFirstIteratorIsEmptyBug() { List empty = new ArrayList(); List notEmpty = new ArrayList(); notEmpty.add("A"); notEmpty.add("B"); notEmpty.add("C"); IteratorChain chain = new IteratorChain(); chain.addIterator(empty.iterator()); chain.addIterator(notEmpty.iterator()); assertTrue("should have next", chain.hasNext()); assertEquals("A", chain.next()); assertTrue("should have next", chain.hasNext()); assertEquals("B", chain.next()); assertTrue("should have next", chain.hasNext()); assertEquals("C", chain.next()); assertTrue("should not have next", !chain.hasNext()); } public void testEmptyChain() { IteratorChain chain = new IteratorChain(); assertEquals(false, chain.hasNext()); try { chain.next(); fail(); } catch (NoSuchElementException ex) { } try { chain.remove(); fail(); } catch (IllegalStateException ex) { } } } ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootcollections-generic-4.01/src/test/org/apache/commons/collections15/iterators/TestArrayListIterator2.javacollections-generic-4.01/src/test/org/apache/commons/collections15/iterators/TestArrayListIterator2.0000644000175000017500000000353510464140756034111 0ustar giovannigiovanni/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.iterators; import junit.framework.Test; import junit.framework.TestSuite; import java.util.Iterator; /** * Test the ArrayListIterator class with primitives. * * @author Matt Hall, John Watkinson, Neil O'Toole * @version $Revision: 1.1 $ $Date: 2005/10/11 19:11:58 $ */ public class TestArrayListIterator2 extends TestArrayIterator2 { public TestArrayListIterator2(String testName) { super(testName); } public static Test suite() { return new TestSuite(TestArrayListIterator2.class); } public Iterator makeEmptyIterator() { return new ArrayListIterator(new int[0]); } public Iterator makeFullIterator() { return new ArrayListIterator(testArray); } public ArrayIterator makeArrayIterator() { return (ArrayIterator) makeEmptyIterator(); } public ArrayIterator makeArrayIterator(Object array) { return new ArrayListIterator(array); } public ArrayIterator makeArrayIterator(Object array, int index) { return new ArrayListIterator(array, index); } public ArrayIterator makeArrayIterator(Object array, int start, int end) { return new ArrayListIterator(array, start, end); } } ././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootcollections-generic-4.01/src/test/org/apache/commons/collections15/iterators/TestObjectArrayIterator.javacollections-generic-4.01/src/test/org/apache/commons/collections15/iterators/TestObjectArrayIterator0000644000175000017500000000727410464140763034246 0ustar giovannigiovanni/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.iterators; import junit.framework.Test; import junit.framework.TestSuite; import java.util.Iterator; import java.util.NoSuchElementException; /** * Tests the ObjectArrayIterator. * * @author James Strachan * @author Mauricio S. Moura * @author Morgan Delagrange * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 19:11:58 $ */ public class TestObjectArrayIterator extends AbstractTestIterator { protected String[] testArray = {"One", "Two", "Three"}; public static Test suite() { return new TestSuite(TestObjectArrayIterator.class); } public TestObjectArrayIterator(String testName) { super(testName); } public Iterator makeEmptyIterator() { return new ObjectArrayIterator(new Object[0]); } public Iterator makeFullIterator() { return new ObjectArrayIterator(testArray); } public ObjectArrayIterator makeArrayIterator() { return new ObjectArrayIterator(); } public ObjectArrayIterator makeArrayIterator(Object[] array) { return new ObjectArrayIterator(array); } public ObjectArrayIterator makeArrayIterator(Object[] array, int index) { return new ObjectArrayIterator(array, index); } public ObjectArrayIterator makeArrayIterator(Object[] array, int start, int end) { return new ObjectArrayIterator(array, start, end); } public boolean supportsRemove() { return false; } public void testIterator() { Iterator iter = (Iterator) makeFullIterator(); for (int i = 0; i < testArray.length; i++) { Object testValue = testArray[i]; Object iterValue = iter.next(); assertEquals("Iteration value is correct", testValue, iterValue); } assertTrue("Iterator should now be empty", !iter.hasNext()); try { Object testValue = iter.next(); } catch (Exception e) { assertTrue("NoSuchElementException must be thrown", e.getClass().equals((new NoSuchElementException()).getClass())); } } public void testNullArray() { try { Iterator iter = makeArrayIterator(null); fail("Constructor should throw a NullPointerException when constructed with a null array"); } catch (NullPointerException e) { // expected } ObjectArrayIterator iter = makeArrayIterator(); try { iter.setArray(null); fail("setArray(null) should throw a NullPointerException"); } catch (NullPointerException e) { // expected } } public void testDoubleSet() { ObjectArrayIterator it = makeArrayIterator(); it.setArray(new String[0]); try { it.setArray(new String[0]); fail(); } catch (IllegalStateException ex) { } } public void testReset() { ObjectArrayIterator it = makeArrayIterator(testArray); it.next(); it.reset(); assertEquals("One", it.next()); } } ././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootcollections-generic-4.01/src/test/org/apache/commons/collections15/iterators/AbstractTestMapIterator.javacollections-generic-4.01/src/test/org/apache/commons/collections15/iterators/AbstractTestMapIterator0000644000175000017500000002526610464140755034244 0ustar giovannigiovanni/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.iterators; import org.apache.commons.collections15.MapIterator; import java.util.*; /** * Abstract class for testing the MapIterator interface. *

                  * This class provides a framework for testing an implementation of MapIterator. * Concrete subclasses must provide the list iterator to be tested. * They must also specify certain details of how the list iterator operates by * overriding the supportsXxx() methods if necessary. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 19:11:58 $ * @since Commons Collections 3.0 */ public abstract class AbstractTestMapIterator extends AbstractTestIterator { /** * JUnit constructor. * * @param testName the test class name */ public AbstractTestMapIterator(String testName) { super(testName); } //----------------------------------------------------------------------- /** * Implement this method to return a map iterator over an empty map. * * @return an empty iterator */ public abstract MapIterator makeEmptyMapIterator(); /** * Implement this method to return a map iterator over a map with elements. * * @return a full iterator */ public abstract MapIterator makeFullMapIterator(); /** * Implement this method to return the map which contains the same data as the * iterator. * * @return a full map which can be updated */ public abstract Map getMap(); /** * Implement this method to return the confirmed map which contains the same * data as the iterator. * * @return a full map which can be updated */ public abstract Map getConfirmedMap(); /** * Implements the abstract superclass method to return the list iterator. * * @return an empty iterator */ public final Iterator makeEmptyIterator() { return makeEmptyMapIterator(); } /** * Implements the abstract superclass method to return the list iterator. * * @return a full iterator */ public final Iterator makeFullIterator() { return makeFullMapIterator(); } /** * Whether or not we are testing an iterator that supports setValue(). * Default is true. * * @return true if Iterator supports set */ public boolean supportsSetValue() { return true; } /** * Whether the get operation on the map structurally modifies the map, * such as with LRUMap. Default is false. * * @return true if the get method structurally modifies the map */ public boolean isGetStructuralModify() { return false; } /** * The values to be used in the add and set tests. * Default is two strings. */ public Object[] addSetValues() { return new Object[]{"A", "B"}; } //----------------------------------------------------------------------- /** * Test that the empty list iterator contract is correct. */ public void testEmptyMapIterator() { if (supportsEmptyIterator() == false) { return; } MapIterator it = makeEmptyMapIterator(); Map map = getMap(); assertEquals(false, it.hasNext()); // next() should throw a NoSuchElementException try { it.next(); fail(); } catch (NoSuchElementException ex) { } // getKey() should throw an IllegalStateException try { it.getKey(); fail(); } catch (IllegalStateException ex) { } // getValue() should throw an IllegalStateException try { it.getValue(); fail(); } catch (IllegalStateException ex) { } if (supportsSetValue() == false) { // setValue() should throw an UnsupportedOperationException/IllegalStateException try { it.setValue(addSetValues()[0]); fail(); } catch (UnsupportedOperationException ex) { } catch (IllegalStateException ex) { } } else { // setValue() should throw an IllegalStateException try { it.setValue(addSetValues()[0]); fail(); } catch (IllegalStateException ex) { } } } //----------------------------------------------------------------------- /** * Test that the full list iterator contract is correct. */ public void testFullMapIterator() { if (supportsFullIterator() == false) { return; } MapIterator it = makeFullMapIterator(); Map map = getMap(); assertEquals(true, it.hasNext()); assertEquals(true, it.hasNext()); Set set = new HashSet(); while (it.hasNext()) { // getKey Object key = it.next(); assertSame("it.next() should equals getKey()", key, it.getKey()); assertTrue("Key must be in map", map.containsKey(key)); assertTrue("Key must be unique", set.add(key)); // getValue Object value = it.getValue(); if (isGetStructuralModify() == false) { assertSame("Value must be mapped to key", map.get(key), value); } assertTrue("Value must be in map", map.containsValue(value)); verify(); } } //----------------------------------------------------------------------- public void testMapIteratorSet() { if (supportsFullIterator() == false) { return; } Object newValue = addSetValues()[0]; Object newValue2 = (addSetValues().length == 1 ? addSetValues()[0] : addSetValues()[1]); MapIterator it = makeFullMapIterator(); Map map = getMap(); Map confirmed = getConfirmedMap(); assertEquals(true, it.hasNext()); Object key = it.next(); Object value = it.getValue(); if (supportsSetValue() == false) { try { it.setValue(newValue); fail(); } catch (UnsupportedOperationException ex) { } return; } Object old = it.setValue(newValue); confirmed.put(key, newValue); assertSame("Key must not change after setValue", key, it.getKey()); assertSame("Value must be changed after setValue", newValue, it.getValue()); assertSame("setValue must return old value", value, old); assertEquals("Map must contain key", true, map.containsKey(key)); // test against confirmed, as map may contain value twice assertEquals("Map must not contain old value", confirmed.containsValue(old), map.containsValue(old)); assertEquals("Map must contain new value", true, map.containsValue(newValue)); verify(); it.setValue(newValue); // same value - should be OK confirmed.put(key, newValue); assertSame("Key must not change after setValue", key, it.getKey()); assertSame("Value must be changed after setValue", newValue, it.getValue()); verify(); it.setValue(newValue2); // new value confirmed.put(key, newValue2); assertSame("Key must not change after setValue", key, it.getKey()); assertSame("Value must be changed after setValue", newValue2, it.getValue()); verify(); } //----------------------------------------------------------------------- public void testRemove() { // override MapIterator it = makeFullMapIterator(); Map map = getMap(); Map confirmed = getConfirmedMap(); assertEquals(true, it.hasNext()); Object key = it.next(); if (supportsRemove() == false) { try { it.remove(); fail(); } catch (UnsupportedOperationException ex) { } return; } it.remove(); confirmed.remove(key); assertEquals(false, map.containsKey(key)); verify(); try { it.remove(); // second remove fails } catch (IllegalStateException ex) { } verify(); } //----------------------------------------------------------------------- public void testMapIteratorSetRemoveSet() { if (supportsSetValue() == false || supportsRemove() == false) { return; } Object newValue = addSetValues()[0]; MapIterator it = makeFullMapIterator(); Map map = getMap(); Map confirmed = getConfirmedMap(); assertEquals(true, it.hasNext()); Object key = it.next(); it.setValue(newValue); it.remove(); confirmed.remove(key); verify(); try { it.setValue(newValue); fail(); } catch (IllegalStateException ex) { } verify(); } //----------------------------------------------------------------------- public void testMapIteratorRemoveGetKey() { if (supportsRemove() == false) { return; } MapIterator it = makeFullMapIterator(); Map map = getMap(); Map confirmed = getConfirmedMap(); assertEquals(true, it.hasNext()); Object key = it.next(); it.remove(); confirmed.remove(key); verify(); try { it.getKey(); fail(); } catch (IllegalStateException ex) { } verify(); } //----------------------------------------------------------------------- public void testMapIteratorRemoveGetValue() { if (supportsRemove() == false) { return; } MapIterator it = makeFullMapIterator(); Map map = getMap(); Map confirmed = getConfirmedMap(); assertEquals(true, it.hasNext()); Object key = it.next(); it.remove(); confirmed.remove(key); verify(); try { it.getValue(); fail(); } catch (IllegalStateException ex) { } verify(); } } ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootcollections-generic-4.01/src/test/org/apache/commons/collections15/iterators/TestSingletonIterator.javacollections-generic-4.01/src/test/org/apache/commons/collections15/iterators/TestSingletonIterator.j0000644000175000017500000000633410464140754034227 0ustar giovannigiovanni/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.iterators; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.collections15.ResettableIterator; import java.util.Iterator; import java.util.NoSuchElementException; /** * Tests the SingletonIterator to ensure that the next() method will actually * perform the iteration rather than the hasNext() method. * * @author Matt Hall, John Watkinson, James Strachan * @version $Revision: 1.1 $ $Date: 2005/10/11 19:11:58 $ */ public class TestSingletonIterator extends AbstractTestIterator { private static final Object testValue = "foo"; public static Test suite() { return new TestSuite(TestSingletonIterator.class); } public TestSingletonIterator(String testName) { super(testName); } /** * Returns a SingletonIterator from which * the element has already been removed. */ public Iterator makeEmptyIterator() { SingletonIterator iter = (SingletonIterator) makeFullIterator(); iter.next(); iter.remove(); iter.reset(); return iter; } public Iterator makeFullIterator() { return new SingletonIterator(testValue); } public boolean supportsRemove() { return true; } public boolean supportsEmptyIterator() { return true; } public void testIterator() { Iterator iter = (Iterator) makeObject(); assertTrue("Iterator has a first item", iter.hasNext()); Object iterValue = iter.next(); assertEquals("Iteration value is correct", testValue, iterValue); assertTrue("Iterator should now be empty", !iter.hasNext()); try { iter.next(); } catch (Exception e) { assertTrue("NoSuchElementException must be thrown", e.getClass().equals((new NoSuchElementException()).getClass())); } } public void testSingletonIteratorRemove() { ResettableIterator iter = new SingletonIterator("xyzzy"); assertTrue(iter.hasNext()); assertEquals("xyzzy", iter.next()); iter.remove(); iter.reset(); assertTrue(!iter.hasNext()); } public void testReset() { ResettableIterator it = (ResettableIterator) makeObject(); assertEquals(true, it.hasNext()); assertEquals(testValue, it.next()); assertEquals(false, it.hasNext()); it.reset(); assertEquals(true, it.hasNext()); assertEquals(testValue, it.next()); assertEquals(false, it.hasNext()); it.reset(); it.reset(); assertEquals(true, it.hasNext()); } } ././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootcollections-generic-4.01/src/test/org/apache/commons/collections15/iterators/AbstractTestListIterator.javacollections-generic-4.01/src/test/org/apache/commons/collections15/iterators/AbstractTestListIterato0000644000175000017500000002053410464140763034250 0ustar giovannigiovanni/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.iterators; import java.util.ArrayList; import java.util.Iterator; import java.util.ListIterator; import java.util.NoSuchElementException; /** * Abstract class for testing the ListIterator interface. *

                  * This class provides a framework for testing an implementation of ListIterator. * Concrete subclasses must provide the list iterator to be tested. * They must also specify certain details of how the list iterator operates by * overriding the supportsXxx() methods if necessary. * * @author Rodney Waldhoff * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 19:11:58 $ * @since Commons Collections 3.0 */ public abstract class AbstractTestListIterator extends AbstractTestIterator { /** * JUnit constructor. * * @param testName the test class name */ public AbstractTestListIterator(String testName) { super(testName); } //----------------------------------------------------------------------- /** * Implement this method to return a list iterator over an empty collection. * * @return an empty iterator */ public abstract ListIterator makeEmptyListIterator(); /** * Implement this method to return a list iterator over a collection with elements. * * @return a full iterator */ public abstract ListIterator makeFullListIterator(); /** * Implements the abstract superclass method to return the list iterator. * * @return an empty iterator */ public Iterator makeEmptyIterator() { return makeEmptyListIterator(); } /** * Implements the abstract superclass method to return the list iterator. * * @return a full iterator */ public Iterator makeFullIterator() { return makeFullListIterator(); } /** * Whether or not we are testing an iterator that supports add(). * Default is true. * * @return true if Iterator supports add */ public boolean supportsAdd() { return true; } /** * Whether or not we are testing an iterator that supports set(). * Default is true. * * @return true if Iterator supports set */ public boolean supportsSet() { return true; } /** * The value to be used in the add and set tests. * Default is null. */ public Object addSetValue() { return null; } //----------------------------------------------------------------------- /** * Test that the empty list iterator contract is correct. */ public void testEmptyListIteratorIsIndeedEmpty() { if (supportsEmptyIterator() == false) { return; } ListIterator it = makeEmptyListIterator(); assertEquals(false, it.hasNext()); assertEquals(0, it.nextIndex()); assertEquals(false, it.hasPrevious()); assertEquals(-1, it.previousIndex()); // next() should throw a NoSuchElementException try { it.next(); fail("NoSuchElementException must be thrown from empty ListIterator"); } catch (NoSuchElementException e) { } // previous() should throw a NoSuchElementException try { it.previous(); fail("NoSuchElementException must be thrown from empty ListIterator"); } catch (NoSuchElementException e) { } } /** * Test navigation through the iterator. */ public void testWalkForwardAndBack() { ArrayList list = new ArrayList(); ListIterator it = makeFullListIterator(); while (it.hasNext()) { list.add(it.next()); } // check state at end assertEquals(false, it.hasNext()); assertEquals(true, it.hasPrevious()); try { it.next(); fail("NoSuchElementException must be thrown from next at end of ListIterator"); } catch (NoSuchElementException e) { } // loop back through comparing for (int i = list.size() - 1; i >= 0; i--) { assertEquals(i + 1, it.nextIndex()); assertEquals(i, it.previousIndex()); Object obj = list.get(i); assertEquals(obj, it.previous()); } // check state at start assertEquals(true, it.hasNext()); assertEquals(false, it.hasPrevious()); try { it.previous(); fail("NoSuchElementException must be thrown from previous at start of ListIterator"); } catch (NoSuchElementException e) { } } /** * Test add behaviour. */ public void testAdd() { ListIterator it = makeFullListIterator(); Object addValue = addSetValue(); if (supportsAdd() == false) { // check for UnsupportedOperationException if not supported try { it.add(addValue); } catch (UnsupportedOperationException ex) { } return; } // add at start should be OK, added should be previous it = makeFullListIterator(); it.add(addValue); assertEquals(addValue, it.previous()); // add at start should be OK, added should not be next it = makeFullListIterator(); it.add(addValue); assertTrue(addValue != it.next()); // add in middle and at end should be OK it = makeFullListIterator(); while (it.hasNext()) { it.next(); it.add(addValue); // check add OK assertEquals(addValue, it.previous()); it.next(); } } /** * Test set behaviour. */ public void testSet() { ListIterator it = makeFullListIterator(); if (supportsSet() == false) { // check for UnsupportedOperationException if not supported try { it.set(addSetValue()); } catch (UnsupportedOperationException ex) { } return; } // should throw IllegalStateException before next() called try { it.set(addSetValue()); fail(); } catch (IllegalStateException ex) { } // set after next should be fine it.next(); it.set(addSetValue()); // repeated set calls should be fine it.set(addSetValue()); } public void testRemoveThenSet() { ListIterator it = makeFullListIterator(); if (supportsRemove() && supportsSet()) { it.next(); it.remove(); try { it.set(addSetValue()); fail("IllegalStateException must be thrown from set after remove"); } catch (IllegalStateException e) { } } } public void testAddThenSet() { ListIterator it = makeFullListIterator(); // add then set if (supportsAdd() && supportsSet()) { it.next(); it.add(addSetValue()); try { it.set(addSetValue()); fail("IllegalStateException must be thrown from set after add"); } catch (IllegalStateException e) { } } } /** * Test remove after add behaviour. */ public void testAddThenRemove() { ListIterator it = makeFullListIterator(); // add then remove if (supportsAdd() && supportsRemove()) { it.next(); it.add(addSetValue()); try { it.remove(); fail("IllegalStateException must be thrown from remove after add"); } catch (IllegalStateException e) { } } } } ././@LongLink0000000000000000000000000000015600000000000011567 Lustar rootrootcollections-generic-4.01/src/test/org/apache/commons/collections15/iterators/TestUnmodifiableMapIterator.javacollections-generic-4.01/src/test/org/apache/commons/collections15/iterators/TestUnmodifiableMapIter0000644000175000017500000000546110464140754034203 0ustar giovannigiovanni/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.iterators; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.collections15.BidiMap; import org.apache.commons.collections15.MapIterator; import org.apache.commons.collections15.Unmodifiable; import org.apache.commons.collections15.bidimap.DualHashBidiMap; import java.util.HashMap; import java.util.Map; /** * Tests the UnmodifiableMapIterator. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 19:11:58 $ */ public class TestUnmodifiableMapIterator extends AbstractTestMapIterator { public static Test suite() { return new TestSuite(TestUnmodifiableMapIterator.class); } public TestUnmodifiableMapIterator(String testName) { super(testName); } public MapIterator makeEmptyMapIterator() { return UnmodifiableMapIterator.decorate(new DualHashBidiMap().mapIterator()); } public MapIterator makeFullMapIterator() { return UnmodifiableMapIterator.decorate(((BidiMap) getMap()).mapIterator()); } public Map getMap() { Map testMap = new DualHashBidiMap(); testMap.put("A", "a"); testMap.put("B", "b"); testMap.put("C", "c"); return testMap; } public Map getConfirmedMap() { Map testMap = new HashMap(); testMap.put("A", "a"); testMap.put("B", "b"); testMap.put("C", "c"); return testMap; } public boolean supportsRemove() { return false; } public boolean supportsSetValue() { return false; } //----------------------------------------------------------------------- public void testMapIterator() { assertTrue(makeEmptyMapIterator() instanceof Unmodifiable); } public void testDecorateFactory() { MapIterator it = makeFullMapIterator(); assertSame(it, UnmodifiableMapIterator.decorate(it)); it = ((BidiMap) getMap()).mapIterator(); assertTrue(it != UnmodifiableMapIterator.decorate(it)); try { UnmodifiableMapIterator.decorate(null); fail(); } catch (IllegalArgumentException ex) { } } } ././@LongLink0000000000000000000000000000015600000000000011567 Lustar rootrootcollections-generic-4.01/src/test/org/apache/commons/collections15/iterators/TestObjectArrayListIterator.javacollections-generic-4.01/src/test/org/apache/commons/collections15/iterators/TestObjectArrayListIter0000644000175000017500000000720710464140754034210 0ustar giovannigiovanni/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.iterators; import junit.framework.Test; import junit.framework.TestSuite; import java.util.Arrays; import java.util.Iterator; import java.util.ListIterator; import java.util.NoSuchElementException; /** * Tests the ObjectArrayListIterator class. * * @author Matt Hall, John Watkinson, Neil O'Toole * @version $Revision: 1.1 $ $Date: 2005/10/11 19:11:58 $ */ public class TestObjectArrayListIterator extends TestObjectArrayIterator { public TestObjectArrayListIterator(String testName) { super(testName); } public static Test suite() { return new TestSuite(TestObjectArrayListIterator.class); } public Iterator makeEmptyIterator() { return new ObjectArrayListIterator(new Object[0]); } public Iterator makeFullIterator() { return new ObjectArrayListIterator(testArray); } public ListIterator makeArrayListIterator(Object[] array) { return new ObjectArrayListIterator(array); } /** * Test the basic ListIterator functionality - going backwards using * previous(). */ public void testListIterator() { ListIterator iter = (ListIterator) makeFullIterator(); // TestArrayIterator#testIterator() has already tested the iterator forward, // now we need to test it in reverse // fast-forward the iterator to the end... while (iter.hasNext()) { iter.next(); } for (int x = testArray.length - 1; x >= 0; x--) { Object testValue = testArray[x]; Object iterValue = iter.previous(); assertEquals("Iteration value is correct", testValue, iterValue); } assertTrue("Iterator should now be empty", !iter.hasPrevious()); try { Object testValue = iter.previous(); } catch (Exception e) { assertTrue("NoSuchElementException must be thrown", e.getClass().equals((new NoSuchElementException()).getClass())); } } /** * Tests the {@link java.util.ListIterator#set} operation. */ public void testListIteratorSet() { String[] testData = new String[]{"a", "b", "c"}; String[] result = new String[]{"0", "1", "2"}; ListIterator iter = (ListIterator) makeArrayListIterator(testData); int x = 0; while (iter.hasNext()) { iter.next(); iter.set(Integer.toString(x)); x++; } assertTrue("The two arrays should have the same value, i.e. {0,1,2}", Arrays.equals(testData, result)); // a call to set() before a call to next() or previous() should throw an IllegalStateException iter = makeArrayListIterator(testArray); try { iter.set("should fail"); fail("ListIterator#set should fail if next() or previous() have not yet been called."); } catch (IllegalStateException e) { // expected } catch (Throwable t) { // should never happen fail(t.toString()); } } } ././@LongLink0000000000000000000000000000016500000000000011567 Lustar rootrootcollections-generic-4.01/src/test/org/apache/commons/collections15/iterators/TestUnmodifiableOrderedMapIterator.javacollections-generic-4.01/src/test/org/apache/commons/collections15/iterators/TestUnmodifiableOrdered0000644000175000017500000000604410464140756034226 0ustar giovannigiovanni/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.iterators; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.collections15.MapIterator; import org.apache.commons.collections15.OrderedMap; import org.apache.commons.collections15.OrderedMapIterator; import org.apache.commons.collections15.Unmodifiable; import org.apache.commons.collections15.map.ListOrderedMap; import java.util.HashMap; import java.util.Map; import java.util.TreeMap; /** * Tests the UnmodifiableOrderedMapIterator. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 19:11:58 $ */ public class TestUnmodifiableOrderedMapIterator extends AbstractTestOrderedMapIterator { public static Test suite() { return new TestSuite(TestUnmodifiableOrderedMapIterator.class); } public TestUnmodifiableOrderedMapIterator(String testName) { super(testName); } public MapIterator makeEmptyMapIterator() { return UnmodifiableOrderedMapIterator.decorate(ListOrderedMap.decorate(new HashMap()).orderedMapIterator()); } public MapIterator makeFullMapIterator() { return UnmodifiableOrderedMapIterator.decorate(((OrderedMap) getMap()).orderedMapIterator()); } public Map getMap() { Map testMap = ListOrderedMap.decorate(new HashMap()); testMap.put("A", "a"); testMap.put("B", "b"); testMap.put("C", "c"); return testMap; } public Map getConfirmedMap() { Map testMap = new TreeMap(); testMap.put("A", "a"); testMap.put("B", "b"); testMap.put("C", "c"); return testMap; } public boolean supportsRemove() { return false; } public boolean supportsSetValue() { return false; } //----------------------------------------------------------------------- public void testOrderedMapIterator() { assertTrue(makeEmptyOrderedMapIterator() instanceof Unmodifiable); } public void testDecorateFactory() { OrderedMapIterator it = makeFullOrderedMapIterator(); assertSame(it, UnmodifiableOrderedMapIterator.decorate(it)); it = ((OrderedMap) getMap()).orderedMapIterator(); assertTrue(it != UnmodifiableOrderedMapIterator.decorate(it)); try { UnmodifiableOrderedMapIterator.decorate(null); fail(); } catch (IllegalArgumentException ex) { } } } ././@LongLink0000000000000000000000000000015700000000000011570 Lustar rootrootcollections-generic-4.01/src/test/org/apache/commons/collections15/iterators/TestUnmodifiableListIterator.javacollections-generic-4.01/src/test/org/apache/commons/collections15/iterators/TestUnmodifiableListIte0000644000175000017500000000464410464140761034217 0ustar giovannigiovanni/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.iterators; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.collections15.Unmodifiable; import java.util.*; /** * Tests the UnmodifiableListIterator. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 19:11:58 $ */ public class TestUnmodifiableListIterator extends AbstractTestListIterator { protected String[] testArray = {"One", "Two", "Three"}; protected List testList = new ArrayList(Arrays.asList(testArray)); public static Test suite() { return new TestSuite(TestUnmodifiableListIterator.class); } public TestUnmodifiableListIterator(String testName) { super(testName); } public ListIterator makeEmptyListIterator() { return UnmodifiableListIterator.decorate(Collections.EMPTY_LIST.listIterator()); } public ListIterator makeFullListIterator() { return UnmodifiableListIterator.decorate(testList.listIterator()); } public boolean supportsRemove() { return false; } public boolean supportsAdd() { return false; } public boolean supportsSet() { return false; } //----------------------------------------------------------------------- public void testListIterator() { assertTrue(makeEmptyListIterator() instanceof Unmodifiable); } public void testDecorateFactory() { ListIterator it = makeFullListIterator(); assertSame(it, UnmodifiableListIterator.decorate(it)); it = testList.listIterator(); assertTrue(it != UnmodifiableListIterator.decorate(it)); try { UnmodifiableListIterator.decorate(null); fail(); } catch (IllegalArgumentException ex) { } } } ././@LongLink0000000000000000000000000000015400000000000011565 Lustar rootrootcollections-generic-4.01/src/test/org/apache/commons/collections15/iterators/TestSingletonListIterator.javacollections-generic-4.01/src/test/org/apache/commons/collections15/iterators/TestSingletonListIterat0000644000175000017500000001120410464140760034257 0ustar giovannigiovanni/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.iterators; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.collections15.ResettableListIterator; import java.util.ListIterator; import java.util.NoSuchElementException; /** * Tests the SingletonListIterator. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 19:11:58 $ */ public class TestSingletonListIterator extends AbstractTestListIterator { private static final Object testValue = "foo"; public static Test suite() { return new TestSuite(TestSingletonListIterator.class); } public TestSingletonListIterator(String testName) { super(testName); } /** * Returns a SingletonListIterator from which * the element has already been removed. */ public ListIterator makeEmptyListIterator() { SingletonListIterator iter = (SingletonListIterator) makeFullIterator(); iter.next(); iter.remove(); iter.reset(); return iter; } public ListIterator makeFullListIterator() { return new SingletonListIterator(testValue); } public boolean supportsAdd() { return false; } public boolean supportsRemove() { return true; } public boolean supportsEmptyIterator() { return true; } public void testIterator() { ListIterator iter = (ListIterator) makeObject(); assertTrue("Iterator should have next item", iter.hasNext()); assertTrue("Iterator should have no previous item", !iter.hasPrevious()); assertEquals("Iteration next index", 0, iter.nextIndex()); assertEquals("Iteration previous index", -1, iter.previousIndex()); Object iterValue = iter.next(); assertEquals("Iteration value is correct", testValue, iterValue); assertTrue("Iterator should have no next item", !iter.hasNext()); assertTrue("Iterator should have previous item", iter.hasPrevious()); assertEquals("Iteration next index", 1, iter.nextIndex()); assertEquals("Iteration previous index", 0, iter.previousIndex()); iterValue = iter.previous(); assertEquals("Iteration value is correct", testValue, iterValue); assertTrue("Iterator should have next item", iter.hasNext()); assertTrue("Iterator should have no previous item", !iter.hasPrevious()); assertEquals("Iteration next index", 0, iter.nextIndex()); assertEquals("Iteration previous index", -1, iter.previousIndex()); iterValue = iter.next(); assertEquals("Iteration value is correct", testValue, iterValue); assertTrue("Iterator should have no next item", !iter.hasNext()); assertTrue("Iterator should have previous item", iter.hasPrevious()); assertEquals("Iteration next index", 1, iter.nextIndex()); assertEquals("Iteration previous index", 0, iter.previousIndex()); try { iter.next(); } catch (Exception e) { assertTrue("NoSuchElementException must be thrown", e.getClass().equals((new NoSuchElementException()).getClass())); } iter.previous(); try { iter.previous(); } catch (Exception e) { assertTrue("NoSuchElementException must be thrown", e.getClass().equals((new NoSuchElementException()).getClass())); } } public void testReset() { ResettableListIterator it = (ResettableListIterator) makeObject(); assertEquals(true, it.hasNext()); assertEquals(false, it.hasPrevious()); assertEquals(testValue, it.next()); assertEquals(false, it.hasNext()); assertEquals(true, it.hasPrevious()); it.reset(); assertEquals(true, it.hasNext()); assertEquals(false, it.hasPrevious()); assertEquals(testValue, it.next()); assertEquals(false, it.hasNext()); assertEquals(true, it.hasPrevious()); it.reset(); it.reset(); assertEquals(true, it.hasNext()); } } ././@LongLink0000000000000000000000000000016100000000000011563 Lustar rootrootcollections-generic-4.01/src/test/org/apache/commons/collections15/iterators/AbstractTestOrderedMapIterator.javacollections-generic-4.01/src/test/org/apache/commons/collections15/iterators/AbstractTestOrderedMapI0000644000175000017500000001251210464140760034132 0ustar giovannigiovanni/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.iterators; import org.apache.commons.collections15.OrderedMapIterator; import java.util.*; /** * Abstract class for testing the OrderedMapIterator interface. *

                  * This class provides a framework for testing an implementation of MapIterator. * Concrete subclasses must provide the list iterator to be tested. * They must also specify certain details of how the list iterator operates by * overriding the supportsXxx() methods if necessary. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 19:11:58 $ * @since Commons Collections 3.0 */ public abstract class AbstractTestOrderedMapIterator extends AbstractTestMapIterator { /** * JUnit constructor. * * @param testName the test class name */ public AbstractTestOrderedMapIterator(String testName) { super(testName); } //----------------------------------------------------------------------- public final OrderedMapIterator makeEmptyOrderedMapIterator() { return (OrderedMapIterator) makeEmptyMapIterator(); } public final OrderedMapIterator makeFullOrderedMapIterator() { return (OrderedMapIterator) makeFullMapIterator(); } //----------------------------------------------------------------------- /** * Test that the empty list iterator contract is correct. */ public void testEmptyMapIterator() { if (supportsEmptyIterator() == false) { return; } super.testEmptyMapIterator(); OrderedMapIterator it = makeEmptyOrderedMapIterator(); Map map = getMap(); assertEquals(false, it.hasPrevious()); try { it.previous(); fail(); } catch (NoSuchElementException ex) { } } //----------------------------------------------------------------------- /** * Test that the full list iterator contract is correct. */ public void testFullMapIterator() { if (supportsFullIterator() == false) { return; } super.testFullMapIterator(); OrderedMapIterator it = makeFullOrderedMapIterator(); Map map = getMap(); assertEquals(true, it.hasNext()); assertEquals(false, it.hasPrevious()); Set set = new HashSet(); while (it.hasNext()) { // getKey Object key = it.next(); assertSame("it.next() should equals getKey()", key, it.getKey()); assertTrue("Key must be in map", map.containsKey(key)); assertTrue("Key must be unique", set.add(key)); // getValue Object value = it.getValue(); if (isGetStructuralModify() == false) { assertSame("Value must be mapped to key", map.get(key), value); } assertTrue("Value must be in map", map.containsValue(value)); assertEquals(true, it.hasPrevious()); verify(); } while (it.hasPrevious()) { // getKey Object key = it.previous(); assertSame("it.previous() should equals getKey()", key, it.getKey()); assertTrue("Key must be in map", map.containsKey(key)); assertTrue("Key must be unique", set.remove(key)); // getValue Object value = it.getValue(); if (isGetStructuralModify() == false) { assertSame("Value must be mapped to key", map.get(key), value); } assertTrue("Value must be in map", map.containsValue(value)); assertEquals(true, it.hasNext()); verify(); } } //----------------------------------------------------------------------- /** * Test that the iterator order matches the keySet order. */ public void testMapIteratorOrder() { if (supportsFullIterator() == false) { return; } OrderedMapIterator it = makeFullOrderedMapIterator(); Map map = getMap(); assertEquals("keySet() not consistent", new ArrayList(map.keySet()), new ArrayList(map.keySet())); Iterator it2 = map.keySet().iterator(); assertEquals(true, it.hasNext()); assertEquals(true, it2.hasNext()); List list = new ArrayList(); while (it.hasNext()) { Object key = it.next(); assertEquals(it2.next(), key); list.add(key); } assertEquals(map.size(), list.size()); while (it.hasPrevious()) { Object key = it.previous(); assertEquals(list.get(list.size() - 1), key); list.remove(list.size() - 1); } assertEquals(0, list.size()); } } ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootcollections-generic-4.01/src/test/org/apache/commons/collections15/iterators/TestFilterListIterator.javacollections-generic-4.01/src/test/org/apache/commons/collections15/iterators/TestFilterListIterator.0000644000175000017500000003706510464140755034202 0ustar giovannigiovanni/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.iterators; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.apache.commons.collections15.Predicate; import java.util.ArrayList; import java.util.List; import java.util.ListIterator; import java.util.Random; /** * Tests the FilterListIterator class. * * @author Matt Hall, John Watkinson, Rodney Waldhoff * @version $Revision: 1.1 $ $Date: 2005/10/11 19:11:58 $ */ public class TestFilterListIterator extends TestCase { public TestFilterListIterator(String testName) { super(testName); } public static Test suite() { return new TestSuite(TestFilterListIterator.class); } public static void main(String args[]) { String[] testCaseName = {TestFilterListIterator.class.getName()}; junit.textui.TestRunner.main(testCaseName); } private ArrayList list = null; private ArrayList odds = null; private ArrayList evens = null; private ArrayList threes = null; private ArrayList fours = null; private ArrayList sixes = null; private Predicate truePred = null; private Predicate falsePred = null; private Predicate evenPred = null; private Predicate oddPred = null; private Predicate threePred = null; private Predicate fourPred = null; private Random random = new Random(); public void setUp() { list = new ArrayList(); odds = new ArrayList(); evens = new ArrayList(); threes = new ArrayList(); fours = new ArrayList(); sixes = new ArrayList(); for (int i = 0; i < 20; i++) { list.add(new Integer(i)); if (i % 2 == 0) { evens.add(new Integer(i)); } if (i % 2 == 1) { odds.add(new Integer(i)); } if (i % 3 == 0) { threes.add(new Integer(i)); } if (i % 4 == 0) { fours.add(new Integer(i)); } if (i % 6 == 0) { sixes.add(new Integer(i)); } } truePred = new Predicate() { public boolean evaluate(Object x) { return true; } }; falsePred = new Predicate() { public boolean evaluate(Object x) { return true; } }; evenPred = new Predicate() { public boolean evaluate(Object x) { return (((Integer) x).intValue() % 2 == 0); } }; oddPred = new Predicate() { public boolean evaluate(Object x) { return (((Integer) x).intValue() % 2 == 1); } }; threePred = new Predicate() { public boolean evaluate(Object x) { return (((Integer) x).intValue() % 3 == 0); } }; fourPred = new Predicate() { public boolean evaluate(Object x) { return (((Integer) x).intValue() % 4 == 0); } }; } public void tearDown() throws Exception { list = null; odds = null; evens = null; threes = null; fours = null; sixes = null; truePred = null; falsePred = null; evenPred = null; oddPred = null; threePred = null; fourPred = null; } public void testWalkLists() { // this just confirms that our walkLists method works OK walkLists(list, list.listIterator()); } public void testManual() { // do this one "by hand" as a sanity check FilterListIterator filtered = new FilterListIterator(list.listIterator(), threePred); assertEquals(new Integer(0), filtered.next()); assertEquals(new Integer(3), filtered.next()); assertEquals(new Integer(6), filtered.next()); assertEquals(new Integer(9), filtered.next()); assertEquals(new Integer(12), filtered.next()); assertEquals(new Integer(15), filtered.next()); assertEquals(new Integer(18), filtered.next()); assertEquals(new Integer(18), filtered.previous()); assertEquals(new Integer(15), filtered.previous()); assertEquals(new Integer(12), filtered.previous()); assertEquals(new Integer(9), filtered.previous()); assertEquals(new Integer(6), filtered.previous()); assertEquals(new Integer(3), filtered.previous()); assertEquals(new Integer(0), filtered.previous()); assertTrue(!filtered.hasPrevious()); assertEquals(new Integer(0), filtered.next()); assertEquals(new Integer(3), filtered.next()); assertEquals(new Integer(6), filtered.next()); assertEquals(new Integer(9), filtered.next()); assertEquals(new Integer(12), filtered.next()); assertEquals(new Integer(15), filtered.next()); assertEquals(new Integer(18), filtered.next()); assertTrue(!filtered.hasNext()); assertEquals(new Integer(18), filtered.previous()); assertEquals(new Integer(15), filtered.previous()); assertEquals(new Integer(12), filtered.previous()); assertEquals(new Integer(9), filtered.previous()); assertEquals(new Integer(6), filtered.previous()); assertEquals(new Integer(3), filtered.previous()); assertEquals(new Integer(0), filtered.previous()); assertEquals(new Integer(0), filtered.next()); assertEquals(new Integer(0), filtered.previous()); assertEquals(new Integer(0), filtered.next()); assertEquals(new Integer(3), filtered.next()); assertEquals(new Integer(6), filtered.next()); assertEquals(new Integer(6), filtered.previous()); assertEquals(new Integer(3), filtered.previous()); assertEquals(new Integer(3), filtered.next()); assertEquals(new Integer(6), filtered.next()); assertEquals(new Integer(9), filtered.next()); assertEquals(new Integer(12), filtered.next()); assertEquals(new Integer(15), filtered.next()); assertEquals(new Integer(15), filtered.previous()); assertEquals(new Integer(12), filtered.previous()); assertEquals(new Integer(9), filtered.previous()); } public void testTruePredicate() { FilterListIterator filtered = new FilterListIterator(list.listIterator(), truePred); walkLists(list, filtered); } public void testFalsePredicate() { FilterListIterator filtered = new FilterListIterator(list.listIterator(), falsePred); walkLists(new ArrayList(), filtered); } public void testEvens() { FilterListIterator filtered = new FilterListIterator(list.listIterator(), evenPred); walkLists(evens, filtered); } public void testOdds() { FilterListIterator filtered = new FilterListIterator(list.listIterator(), oddPred); walkLists(odds, filtered); } public void testThrees() { FilterListIterator filtered = new FilterListIterator(list.listIterator(), threePred); walkLists(threes, filtered); } public void testFours() { FilterListIterator filtered = new FilterListIterator(list.listIterator(), fourPred); walkLists(fours, filtered); } public void testNestedSixes() { FilterListIterator filtered = new FilterListIterator(new FilterListIterator(list.listIterator(), threePred), evenPred); walkLists(sixes, filtered); } public void testNestedSixes2() { FilterListIterator filtered = new FilterListIterator(new FilterListIterator(list.listIterator(), evenPred), threePred); walkLists(sixes, filtered); } public void testNestedSixes3() { FilterListIterator filtered = new FilterListIterator(new FilterListIterator(list.listIterator(), threePred), evenPred); walkLists(sixes, new FilterListIterator(filtered, truePred)); } public void testNextChangesPrevious() { { FilterListIterator filtered = new FilterListIterator(list.listIterator(), threePred); nextNextPrevious(threes.listIterator(), filtered); } { FilterListIterator filtered = new FilterListIterator(list.listIterator(), truePred); nextNextPrevious(list.listIterator(), filtered); } } public void testPreviousChangesNext() { { FilterListIterator filtered = new FilterListIterator(list.listIterator(), threePred); ListIterator expected = threes.listIterator(); walkForward(expected, filtered); previousPreviousNext(expected, filtered); } { FilterListIterator filtered = new FilterListIterator(list.listIterator(), truePred); ListIterator expected = list.listIterator(); walkForward(expected, filtered); previousPreviousNext(expected, filtered); } } public void testFailingHasNextBug() { FilterListIterator filtered = new FilterListIterator(list.listIterator(), fourPred); ListIterator expected = fours.listIterator(); while (expected.hasNext()) { expected.next(); filtered.next(); } assertTrue(filtered.hasPrevious()); assertTrue(!filtered.hasNext()); assertEquals(expected.previous(), filtered.previous()); } // Utilities private void walkForward(ListIterator expected, ListIterator testing) { while (expected.hasNext()) { assertEquals(expected.nextIndex(), testing.nextIndex()); assertEquals(expected.previousIndex(), testing.previousIndex()); assertTrue(testing.hasNext()); assertEquals(expected.next(), testing.next()); } } private void walkBackward(ListIterator expected, ListIterator testing) { while (expected.hasPrevious()) { assertEquals(expected.nextIndex(), testing.nextIndex()); assertEquals(expected.previousIndex(), testing.previousIndex()); assertTrue(testing.hasPrevious()); assertEquals(expected.previous(), testing.previous()); } } private void nextNextPrevious(ListIterator expected, ListIterator testing) { // calls to next() should change the value returned by previous() // even after previous() has been set by a call to hasPrevious() assertEquals(expected.next(), testing.next()); assertEquals(expected.hasPrevious(), testing.hasPrevious()); Object expecteda = expected.next(); Object testinga = testing.next(); assertEquals(expecteda, testinga); Object expectedb = expected.previous(); Object testingb = testing.previous(); assertEquals(expecteda, expectedb); assertEquals(testinga, testingb); } private void previousPreviousNext(ListIterator expected, ListIterator testing) { // calls to previous() should change the value returned by next() // even after next() has been set by a call to hasNext() assertEquals(expected.previous(), testing.previous()); assertEquals(expected.hasNext(), testing.hasNext()); Object expecteda = expected.previous(); Object testinga = testing.previous(); assertEquals(expecteda, testinga); Object expectedb = expected.next(); Object testingb = testing.next(); assertEquals(expecteda, testingb); assertEquals(expecteda, expectedb); assertEquals(testinga, testingb); } private void walkLists(List list, ListIterator testing) { ListIterator expected = list.listIterator(); // walk all the way forward walkForward(expected, testing); // walk all the way back walkBackward(expected, testing); // forward,back,forward while (expected.hasNext()) { assertEquals(expected.nextIndex(), testing.nextIndex()); assertEquals(expected.previousIndex(), testing.previousIndex()); assertTrue(testing.hasNext()); assertEquals(expected.next(), testing.next()); assertTrue(testing.hasPrevious()); assertEquals(expected.previous(), testing.previous()); assertTrue(testing.hasNext()); assertEquals(expected.next(), testing.next()); } // walk all the way back walkBackward(expected, testing); for (int i = 0; i < list.size(); i++) { // walk forward i for (int j = 0; j < i; j++) { assertEquals(expected.nextIndex(), testing.nextIndex()); assertEquals(expected.previousIndex(), testing.previousIndex()); assertTrue(expected.hasNext()); // if this one fails we've got a logic error in the test assertTrue(testing.hasNext()); assertEquals(expected.next(), testing.next()); } // walk back i/2 for (int j = 0; j < i / 2; j++) { assertEquals(expected.nextIndex(), testing.nextIndex()); assertEquals(expected.previousIndex(), testing.previousIndex()); assertTrue(expected.hasPrevious()); // if this one fails we've got a logic error in the test assertTrue(testing.hasPrevious()); assertEquals(expected.previous(), testing.previous()); } // walk forward i/2 for (int j = 0; j < i / 2; j++) { assertEquals(expected.nextIndex(), testing.nextIndex()); assertEquals(expected.previousIndex(), testing.previousIndex()); assertTrue(expected.hasNext()); // if this one fails we've got a logic error in the test assertTrue(testing.hasNext()); assertEquals(expected.next(), testing.next()); } // walk back i for (int j = 0; j < i; j++) { assertEquals(expected.nextIndex(), testing.nextIndex()); assertEquals(expected.previousIndex(), testing.previousIndex()); assertTrue(expected.hasPrevious()); // if this one fails we've got a logic error in the test assertTrue(testing.hasPrevious()); assertEquals(expected.previous(), testing.previous()); } } // random walk StringBuffer walkdescr = new StringBuffer(500); for (int i = 0; i < 500; i++) { if (random.nextBoolean()) { // step forward walkdescr.append("+"); if (expected.hasNext()) { assertEquals(walkdescr.toString(), expected.next(), testing.next()); } } else { // step backward walkdescr.append("-"); if (expected.hasPrevious()) { assertEquals(walkdescr.toString(), expected.previous(), testing.previous()); } } assertEquals(walkdescr.toString(), expected.nextIndex(), testing.nextIndex()); assertEquals(walkdescr.toString(), expected.previousIndex(), testing.previousIndex()); } } } ././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootcollections-generic-4.01/src/test/org/apache/commons/collections15/iterators/TestUniqueFilterIterator.javacollections-generic-4.01/src/test/org/apache/commons/collections15/iterators/TestUniqueFilterIterato0000644000175000017500000000526010464140763034264 0ustar giovannigiovanni/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.iterators; import junit.framework.Test; import junit.framework.TestSuite; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; /** * Tests the UniqueFilterIterator class. * * @author James Strachan * @author Mauricio S. Moura * @author Morgan Delagrange * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 19:11:58 $ */ public class TestUniqueFilterIterator extends AbstractTestIterator { protected String[] testArray = {"One", "Two", "Three", "Four", "Five", "Six"}; protected List list1 = null; public static Test suite() { return new TestSuite(TestUniqueFilterIterator.class); } public TestUniqueFilterIterator(String testName) { super(testName); } public void setUp() { list1 = new ArrayList(); list1.add("One"); list1.add("Two"); list1.add("Three"); list1.add("Two"); list1.add("One"); list1.add("Four"); list1.add("Five"); list1.add("Five"); list1.add("Six"); list1.add("Five"); } public Iterator makeEmptyIterator() { ArrayList list = new ArrayList(); return new UniqueFilterIterator(list.iterator()); } public Iterator makeFullIterator() { Iterator i = list1.iterator(); return new UniqueFilterIterator(i); } public void testIterator() { Iterator iter = (Iterator) makeFullIterator(); for (int i = 0; i < testArray.length; i++) { Object testValue = testArray[i]; Object iterValue = iter.next(); assertEquals("Iteration value is correct", testValue, iterValue); } assertTrue("Iterator should now be empty", !iter.hasNext()); try { Object testValue = iter.next(); } catch (Exception e) { assertTrue("NoSuchElementException must be thrown", e.getClass().equals((new NoSuchElementException()).getClass())); } } } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootcollections-generic-4.01/src/test/org/apache/commons/collections15/iterators/TestLoopingIterator.javacollections-generic-4.01/src/test/org/apache/commons/collections15/iterators/TestLoopingIterator.jav0000644000175000017500000001541510464140757034226 0ustar giovannigiovanni/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.iterators; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.NoSuchElementException; /** * Tests the LoopingIterator class. * * @author Jonathan Carlson * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 19:11:58 $ */ public class TestLoopingIterator extends TestCase { public TestLoopingIterator(String testName) { super(testName); } public static Test suite() { return new TestSuite(TestLoopingIterator.class); } /** * Tests constructor exception. */ public void testConstructorEx() throws Exception { try { new LoopingIterator(null); fail(); } catch (NullPointerException ex) { } } /** * Tests whether an empty looping iterator works as designed. * * @throws Exception If something unexpected occurs. */ public void testLooping0() throws Exception { List list = new ArrayList(); LoopingIterator loop = new LoopingIterator(list); assertTrue("hasNext should return false", loop.hasNext() == false); try { loop.next(); fail("NoSuchElementException was not thrown during next() call."); } catch (NoSuchElementException ex) { } } /** * Tests whether a populated looping iterator works as designed. * * @throws Exception If something unexpected occurs. */ public void testLooping1() throws Exception { List list = new ArrayList(Arrays.asList(new String[]{"a"})); LoopingIterator loop = new LoopingIterator(list); assertTrue("1st hasNext should return true", loop.hasNext()); assertEquals("a", loop.next()); assertTrue("2nd hasNext should return true", loop.hasNext()); assertEquals("a", loop.next()); assertTrue("3rd hasNext should return true", loop.hasNext()); assertEquals("a", loop.next()); } /** * Tests whether a populated looping iterator works as designed. * * @throws Exception If something unexpected occurs. */ public void testLooping2() throws Exception { List list = new ArrayList(Arrays.asList(new String[]{"a", "b"})); LoopingIterator loop = new LoopingIterator(list); assertTrue("1st hasNext should return true", loop.hasNext()); assertEquals("a", loop.next()); assertTrue("2nd hasNext should return true", loop.hasNext()); assertEquals("b", loop.next()); assertTrue("3rd hasNext should return true", loop.hasNext()); assertEquals("a", loop.next()); } /** * Tests whether a populated looping iterator works as designed. * * @throws Exception If something unexpected occurs. */ public void testLooping3() throws Exception { List list = new ArrayList(Arrays.asList(new String[]{"a", "b", "c"})); LoopingIterator loop = new LoopingIterator(list); assertTrue("1st hasNext should return true", loop.hasNext()); assertEquals("a", loop.next()); assertTrue("2nd hasNext should return true", loop.hasNext()); assertEquals("b", loop.next()); assertTrue("3rd hasNext should return true", loop.hasNext()); assertEquals("c", loop.next()); assertTrue("4th hasNext should return true", loop.hasNext()); assertEquals("a", loop.next()); } /** * Tests the remove() method on a LoopingIterator wrapped ArrayList. * * @throws Exception If something unexpected occurs. */ public void testRemoving1() throws Exception { List list = new ArrayList(Arrays.asList(new String[]{"a", "b", "c"})); LoopingIterator loop = new LoopingIterator(list); assertEquals("list should have 3 elements.", 3, list.size()); assertTrue("1st hasNext should return true", loop.hasNext()); assertEquals("a", loop.next()); loop.remove(); // removes a assertEquals("list should have 2 elements.", 2, list.size()); assertTrue("2nd hasNext should return true", loop.hasNext()); assertEquals("b", loop.next()); loop.remove(); // removes b assertEquals("list should have 1 elements.", 1, list.size()); assertTrue("3rd hasNext should return true", loop.hasNext()); assertEquals("c", loop.next()); loop.remove(); // removes c assertEquals("list should have 0 elements.", 0, list.size()); assertTrue("4th hasNext should return false", loop.hasNext() == false); try { loop.next(); fail("Expected NoSuchElementException to be thrown."); } catch (NoSuchElementException ex) { } } /** * Tests the reset() method on a LoopingIterator wrapped ArrayList. * * @throws Exception If something unexpected occurs. */ public void testReset() throws Exception { List list = new ArrayList(Arrays.asList(new String[]{"a", "b", "c"})); LoopingIterator loop = new LoopingIterator(list); assertEquals("a", loop.next()); assertEquals("b", loop.next()); loop.reset(); assertEquals("a", loop.next()); loop.reset(); assertEquals("a", loop.next()); assertEquals("b", loop.next()); assertEquals("c", loop.next()); loop.reset(); assertEquals("a", loop.next()); assertEquals("b", loop.next()); assertEquals("c", loop.next()); } /** * Tests the size() method on a LoopingIterator wrapped ArrayList. * * @throws Exception If something unexpected occurs. */ public void testSize() throws Exception { List list = new ArrayList(Arrays.asList(new String[]{"a", "b", "c"})); LoopingIterator loop = new LoopingIterator(list); assertEquals(3, loop.size()); loop.next(); loop.next(); assertEquals(3, loop.size()); loop.reset(); assertEquals(3, loop.size()); loop.next(); loop.remove(); assertEquals(2, loop.size()); } } ././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootcollections-generic-4.01/src/test/org/apache/commons/collections15/iterators/TestUnmodifiableIterator.javacollections-generic-4.01/src/test/org/apache/commons/collections15/iterators/TestUnmodifiableIterato0000644000175000017500000000432010464140757034245 0ustar giovannigiovanni/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.iterators; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.collections15.Unmodifiable; import java.util.*; /** * Tests the UnmodifiableIterator. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 19:11:58 $ */ public class TestUnmodifiableIterator extends AbstractTestIterator { protected String[] testArray = {"One", "Two", "Three"}; protected List testList = new ArrayList(Arrays.asList(testArray)); public static Test suite() { return new TestSuite(TestUnmodifiableIterator.class); } public TestUnmodifiableIterator(String testName) { super(testName); } public Iterator makeEmptyIterator() { return UnmodifiableIterator.decorate(Collections.EMPTY_LIST.iterator()); } public Iterator makeFullIterator() { return UnmodifiableIterator.decorate(testList.iterator()); } public boolean supportsRemove() { return false; } //----------------------------------------------------------------------- public void testIterator() { assertTrue(makeEmptyIterator() instanceof Unmodifiable); } public void testDecorateFactory() { Iterator it = makeFullIterator(); assertSame(it, UnmodifiableIterator.decorate(it)); it = testList.iterator(); assertTrue(it != UnmodifiableIterator.decorate(it)); try { UnmodifiableIterator.decorate(null); fail(); } catch (IllegalArgumentException ex) { } } } collections-generic-4.01/src/test/org/apache/commons/collections15/iterators/TestArrayIterator.java0000644000175000017500000000606110464140755034031 0ustar giovannigiovanni/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.iterators; import junit.framework.Test; import junit.framework.TestSuite; import java.util.Iterator; import java.util.NoSuchElementException; /** * Tests the ArrayIterator to ensure that the next() method will actually * perform the iteration rather than the hasNext() method. * The code of this test was supplied by Mauricio S. Moura. * * @author James Strachan * @author Mauricio S. Moura * @author Morgan Delagrange * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 19:11:58 $ */ public class TestArrayIterator extends AbstractTestIterator { protected String[] testArray = {"One", "Two", "Three"}; public static Test suite() { return new TestSuite(TestArrayIterator.class); } public TestArrayIterator(String testName) { super(testName); } public Iterator makeEmptyIterator() { return new ArrayIterator(new Object[0]); } public Iterator makeFullIterator() { return new ArrayIterator(testArray); } public boolean supportsRemove() { return false; } public void testIterator() { Iterator iter = (Iterator) makeFullIterator(); for (int i = 0; i < testArray.length; i++) { Object testValue = testArray[i]; Object iterValue = iter.next(); assertEquals("Iteration value is correct", testValue, iterValue); } assertTrue("Iterator should now be empty", !iter.hasNext()); try { Object testValue = iter.next(); } catch (Exception e) { assertTrue("NoSuchElementException must be thrown", e.getClass().equals((new NoSuchElementException()).getClass())); } } public void testNullArray() { try { Iterator iter = new ArrayIterator(null); fail("Constructor should throw a NullPointerException when constructed with a null array"); } catch (NullPointerException e) { // expected } ArrayIterator iter = new ArrayIterator(); try { iter.setArray(null); fail("setArray(null) should throw a NullPointerException"); } catch (NullPointerException e) { // expected } } public void testReset() { ArrayIterator it = (ArrayIterator) makeFullIterator(); it.next(); it.reset(); assertEquals("One", it.next()); } } ././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootcollections-generic-4.01/src/test/org/apache/commons/collections15/iterators/TestListIteratorWrapper.javacollections-generic-4.01/src/test/org/apache/commons/collections15/iterators/TestListIteratorWrapper0000644000175000017500000000673710464140761034316 0ustar giovannigiovanni/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.iterators; import junit.framework.Test; import junit.framework.TestSuite; import java.util.*; /** * Tests the ListIteratorWrapper to insure that it simulates * a ListIterator correctly. * * @author Matt Hall, John Watkinson, Morgan Delagrange * @version $Revision: 1.1 $ $Date: 2005/10/11 19:11:58 $ */ public class TestListIteratorWrapper extends AbstractTestIterator { protected String[] testArray = {"One", "Two", "Three", "Four", "Five", "Six"}; protected List list1 = null; public static Test suite() { return new TestSuite(TestListIteratorWrapper.class); } public TestListIteratorWrapper(String testName) { super(testName); } public void setUp() { list1 = new ArrayList(); list1.add("One"); list1.add("Two"); list1.add("Three"); list1.add("Four"); list1.add("Five"); list1.add("Six"); } public Iterator makeEmptyIterator() { ArrayList list = new ArrayList(); return new ListIteratorWrapper(list.iterator()); } public Iterator makeFullIterator() { Iterator i = list1.iterator(); return new ListIteratorWrapper(i); } public void testIterator() { ListIterator iter = (ListIterator) makeFullIterator(); for (int i = 0; i < testArray.length; i++) { Object testValue = testArray[i]; Object iterValue = iter.next(); assertEquals("Iteration value is correct", testValue, iterValue); } assertTrue("Iterator should now be empty", !iter.hasNext()); try { Object testValue = iter.next(); } catch (Exception e) { assertTrue("NoSuchElementException must be thrown", e.getClass().equals((new NoSuchElementException()).getClass())); } // now, read it backwards for (int i = testArray.length - 1; i > -1; --i) { Object testValue = testArray[i]; Object iterValue = iter.previous(); assertEquals("Iteration value is correct", testValue, iterValue); } try { Object testValue = iter.previous(); } catch (Exception e) { assertTrue("NoSuchElementException must be thrown", e.getClass().equals((new NoSuchElementException()).getClass())); } // now, read it forwards again for (int i = 0; i < testArray.length; i++) { Object testValue = testArray[i]; Object iterValue = iter.next(); assertEquals("Iteration value is correct", testValue, iterValue); } } public void testRemove() { Iterator iter = (Iterator) makeFullIterator(); try { iter.remove(); fail("FilterIterator does not support the remove() method"); } catch (UnsupportedOperationException e) { } } } ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootcollections-generic-4.01/src/test/org/apache/commons/collections15/iterators/TestCollatingIterator.javacollections-generic-4.01/src/test/org/apache/commons/collections15/iterators/TestCollatingIterator.j0000644000175000017500000001714510464140757034206 0ustar giovannigiovanni/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.iterators; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.collections15.comparators.ComparableComparator; import java.util.ArrayList; import java.util.Comparator; import java.util.Iterator; /** * Unit test suite for {@link CollatingIterator}. * * @author Matt Hall, John Watkinson, Rodney Waldhoff * @version $Revision: 1.1 $ $Date: 2005/10/11 19:11:58 $ */ public class TestCollatingIterator extends AbstractTestIterator { //------------------------------------------------------------ Conventional public TestCollatingIterator(String testName) { super(testName); } public static Test suite() { return new TestSuite(TestCollatingIterator.class); } //--------------------------------------------------------------- Lifecycle private Comparator comparator = null; private ArrayList evens = null; private ArrayList odds = null; private ArrayList fib = null; public void setUp() throws Exception { super.setUp(); comparator = new ComparableComparator(); evens = new ArrayList(); odds = new ArrayList(); for (int i = 0; i < 20; i++) { if (0 == i % 2) { evens.add(new Integer(i)); } else { odds.add(new Integer(i)); } } fib = new ArrayList(); fib.add(new Integer(1)); fib.add(new Integer(1)); fib.add(new Integer(2)); fib.add(new Integer(3)); fib.add(new Integer(5)); fib.add(new Integer(8)); fib.add(new Integer(13)); fib.add(new Integer(21)); } //---------------------------------------------------- TestIterator Methods public Iterator makeEmptyIterator() { return new CollatingIterator(comparator); } public Iterator makeFullIterator() { CollatingIterator iter = new CollatingIterator(comparator); iter.addIterator(evens.iterator()); iter.addIterator(odds.iterator()); iter.addIterator(fib.iterator()); return iter; } //------------------------------------------------------------------- Tests public void testGetSetComparator() { CollatingIterator iter = new CollatingIterator(); assertNull(iter.getComparator()); iter.setComparator(comparator); assertSame(comparator, iter.getComparator()); iter.setComparator(null); assertNull(iter.getComparator()); } public void testIterateEven() { CollatingIterator iter = new CollatingIterator(comparator); iter.addIterator(evens.iterator()); for (int i = 0; i < evens.size(); i++) { assertTrue(iter.hasNext()); assertEquals(evens.get(i), iter.next()); } assertTrue(!iter.hasNext()); } public void testIterateEvenOdd() { CollatingIterator iter = new CollatingIterator(comparator, evens.iterator(), odds.iterator()); for (int i = 0; i < 20; i++) { assertTrue(iter.hasNext()); assertEquals(new Integer(i), iter.next()); } assertTrue(!iter.hasNext()); } public void testIterateOddEven() { CollatingIterator iter = new CollatingIterator(comparator, odds.iterator(), evens.iterator()); for (int i = 0; i < 20; i++) { assertTrue(iter.hasNext()); assertEquals(new Integer(i), iter.next()); } assertTrue(!iter.hasNext()); } public void testIterateEvenEven() { CollatingIterator iter = new CollatingIterator(comparator); iter.addIterator(evens.iterator()); iter.addIterator(evens.iterator()); for (int i = 0; i < evens.size(); i++) { assertTrue(iter.hasNext()); assertEquals(evens.get(i), iter.next()); assertTrue(iter.hasNext()); assertEquals(evens.get(i), iter.next()); } assertTrue(!iter.hasNext()); } public void testIterateFibEvenOdd() { CollatingIterator iter = new CollatingIterator(comparator); iter.addIterator(fib.iterator()); iter.addIterator(evens.iterator()); iter.addIterator(odds.iterator()); assertEquals(new Integer(0), iter.next()); // even 0 assertEquals(new Integer(1), iter.next()); // fib 1 assertEquals(new Integer(1), iter.next()); // fib 1 assertEquals(new Integer(1), iter.next()); // odd 1 assertEquals(new Integer(2), iter.next()); // fib 2 assertEquals(new Integer(2), iter.next()); // even 2 assertEquals(new Integer(3), iter.next()); // fib 3 assertEquals(new Integer(3), iter.next()); // odd 3 assertEquals(new Integer(4), iter.next()); // even 4 assertEquals(new Integer(5), iter.next()); // fib 5 assertEquals(new Integer(5), iter.next()); // odd 5 assertEquals(new Integer(6), iter.next()); // even 6 assertEquals(new Integer(7), iter.next()); // odd 7 assertEquals(new Integer(8), iter.next()); // fib 8 assertEquals(new Integer(8), iter.next()); // even 8 assertEquals(new Integer(9), iter.next()); // odd 9 assertEquals(new Integer(10), iter.next()); // even 10 assertEquals(new Integer(11), iter.next()); // odd 11 assertEquals(new Integer(12), iter.next()); // even 12 assertEquals(new Integer(13), iter.next()); // fib 13 assertEquals(new Integer(13), iter.next()); // odd 13 assertEquals(new Integer(14), iter.next()); // even 14 assertEquals(new Integer(15), iter.next()); // odd 15 assertEquals(new Integer(16), iter.next()); // even 16 assertEquals(new Integer(17), iter.next()); // odd 17 assertEquals(new Integer(18), iter.next()); // even 18 assertEquals(new Integer(19), iter.next()); // odd 19 assertEquals(new Integer(21), iter.next()); // fib 21 assertTrue(!iter.hasNext()); } public void testRemoveFromSingle() { CollatingIterator iter = new CollatingIterator(comparator); iter.addIterator(evens.iterator()); int expectedSize = evens.size(); while (iter.hasNext()) { Integer val = (Integer) (iter.next()); if (val.intValue() % 4 == 0) { expectedSize--; iter.remove(); } } assertEquals(expectedSize, evens.size()); } public void testRemoveFromDouble() { CollatingIterator iter = new CollatingIterator(comparator); iter.addIterator(evens.iterator()); iter.addIterator(odds.iterator()); int expectedSize = evens.size() + odds.size(); while (iter.hasNext()) { Integer val = (Integer) (iter.next()); if (val.intValue() % 4 == 0 || val.intValue() % 3 == 0) { expectedSize--; iter.remove(); } } assertEquals(expectedSize, (evens.size() + odds.size())); } } collections-generic-4.01/src/test/org/apache/commons/collections15/iterators/TestAll.java0000644000175000017500000000476710464140764031764 0ustar giovannigiovanni/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.iterators; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * Entry point for all iterator tests. * * @author Matt Hall, John Watkinson, Rodney Waldhoff * @version $Revision: 1.1 $ $Date: 2005/10/11 19:11:58 $ */ public class TestAll extends TestCase { public TestAll(String testName) { super(testName); } public static Test suite() { TestSuite suite = new TestSuite(); suite.addTest(TestArrayIterator.suite()); suite.addTest(TestArrayIterator2.suite()); suite.addTest(TestArrayListIterator.suite()); suite.addTest(TestArrayListIterator2.suite()); suite.addTest(TestObjectArrayIterator.suite()); suite.addTest(TestObjectArrayListIterator.suite()); suite.addTest(TestObjectArrayListIterator2.suite()); suite.addTest(TestCollatingIterator.suite()); suite.addTest(TestFilterIterator.suite()); suite.addTest(TestFilterListIterator.suite()); suite.addTest(TestIteratorChain.suite()); suite.addTest(TestListIteratorWrapper.suite()); suite.addTest(TestLoopingIterator.suite()); suite.addTest(TestSingletonIterator.suite()); suite.addTest(TestSingletonIterator2.suite()); suite.addTest(TestSingletonListIterator.suite()); suite.addTest(TestObjectGraphIterator.suite()); suite.addTest(TestUniqueFilterIterator.suite()); suite.addTest(TestUnmodifiableIterator.suite()); suite.addTest(TestUnmodifiableListIterator.suite()); suite.addTest(TestUnmodifiableMapIterator.suite()); suite.addTest(TestUnmodifiableOrderedMapIterator.suite()); return suite; } public static void main(String args[]) { String[] testCaseName = {TestAll.class.getName()}; junit.textui.TestRunner.main(testCaseName); } } ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootcollections-generic-4.01/src/test/org/apache/commons/collections15/iterators/TestArrayListIterator.javacollections-generic-4.01/src/test/org/apache/commons/collections15/iterators/TestArrayListIterator.j0000644000175000017500000000722710464140755034202 0ustar giovannigiovanni/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.iterators; import junit.framework.Test; import junit.framework.TestSuite; import java.util.Arrays; import java.util.Iterator; import java.util.ListIterator; import java.util.NoSuchElementException; /** * Test the ArrayListIterator class. * * @author Matt Hall, John Watkinson, Neil O'Toole * @version $Revision: 1.1 $ $Date: 2005/10/11 19:11:58 $ */ public class TestArrayListIterator extends TestArrayIterator { public TestArrayListIterator(String testName) { super(testName); } public static Test suite() { return new TestSuite(TestArrayListIterator.class); } public Iterator makeEmptyIterator() { return new ArrayListIterator(new Object[0]); } public Iterator makeFullIterator() { return new ArrayListIterator(testArray); } public ListIterator makeArrayListIterator(Object array) { return new ArrayListIterator(array); } public boolean supportsRemove() { return false; } /** * Test the basic ListIterator functionality - going backwards using * previous(). */ public void testListIterator() { ListIterator iter = (ListIterator) makeFullIterator(); // TestArrayIterator#testIterator() has already tested the iterator forward, // now we need to test it in reverse // fast-forward the iterator to the end... while (iter.hasNext()) { iter.next(); } for (int x = testArray.length - 1; x >= 0; x--) { Object testValue = testArray[x]; Object iterValue = iter.previous(); assertEquals("Iteration value is correct", testValue, iterValue); } assertTrue("Iterator should now be empty", !iter.hasPrevious()); try { Object testValue = iter.previous(); } catch (Exception e) { assertTrue("NoSuchElementException must be thrown", e.getClass().equals((new NoSuchElementException()).getClass())); } } /** * Tests the {@link java.util.ListIterator#set} operation. */ public void testListIteratorSet() { String[] testData = new String[]{"a", "b", "c"}; String[] result = new String[]{"0", "1", "2"}; ListIterator iter = (ListIterator) makeArrayListIterator(testData); int x = 0; while (iter.hasNext()) { iter.next(); iter.set(Integer.toString(x)); x++; } assertTrue("The two arrays should have the same value, i.e. {0,1,2}", Arrays.equals(testData, result)); // a call to set() before a call to next() or previous() should throw an IllegalStateException iter = makeArrayListIterator(testArray); try { iter.set("should fail"); fail("ListIterator#set should fail if next() or previous() have not yet been called."); } catch (IllegalStateException e) { // expected } catch (Throwable t) { // should never happen fail(t.toString()); } } } ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootcollections-generic-4.01/src/test/org/apache/commons/collections15/iterators/TestSingletonIterator2.javacollections-generic-4.01/src/test/org/apache/commons/collections15/iterators/TestSingletonIterator2.0000644000175000017500000000577010464140761034140 0ustar giovannigiovanni/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.iterators; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.collections15.ResettableIterator; import java.util.Iterator; import java.util.NoSuchElementException; /** * Tests the SingletonIterator to ensure that the next() method will actually * perform the iteration rather than the hasNext() method. * * @author Matt Hall, John Watkinson, James Strachan * @version $Revision: 1.1 $ $Date: 2005/10/11 19:11:58 $ */ public class TestSingletonIterator2 extends AbstractTestIterator { private static final Object testValue = "foo"; public static Test suite() { return new TestSuite(TestSingletonIterator2.class); } public TestSingletonIterator2(String testName) { super(testName); } //----------------------------------------------------------------------- public Iterator makeEmptyIterator() { SingletonIterator iter = new SingletonIterator(testValue); iter.next(); iter.remove(); iter.reset(); return iter; } public Iterator makeFullIterator() { return new SingletonIterator(testValue, false); } public boolean supportsRemove() { return false; } public boolean supportsEmptyIterator() { return false; } //----------------------------------------------------------------------- public void testIterator() { Iterator iter = (Iterator) makeObject(); assertTrue("Iterator has a first item", iter.hasNext()); Object iterValue = iter.next(); assertEquals("Iteration value is correct", testValue, iterValue); assertTrue("Iterator should now be empty", !iter.hasNext()); try { iter.next(); } catch (Exception e) { assertTrue("NoSuchElementException must be thrown", e.getClass().equals((new NoSuchElementException()).getClass())); } } public void testReset() { ResettableIterator it = (ResettableIterator) makeObject(); assertEquals(true, it.hasNext()); assertEquals(testValue, it.next()); assertEquals(false, it.hasNext()); it.reset(); assertEquals(true, it.hasNext()); assertEquals(testValue, it.next()); assertEquals(false, it.hasNext()); it.reset(); it.reset(); assertEquals(true, it.hasNext()); } } ././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootcollections-generic-4.01/src/test/org/apache/commons/collections15/iterators/TestObjectGraphIterator.javacollections-generic-4.01/src/test/org/apache/commons/collections15/iterators/TestObjectGraphIterator0000644000175000017500000003254710464140761034230 0ustar giovannigiovanni/* * Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.iterators; import junit.framework.Test; import junit.framework.TestSuite; import junit.textui.TestRunner; import org.apache.commons.collections15.IteratorUtils; import org.apache.commons.collections15.Transformer; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; /** * Testcase. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 19:11:58 $ */ public class TestObjectGraphIterator extends AbstractTestIterator { protected String[] testArray = {"One", "Two", "Three", "Four", "Five", "Six"}; protected List list1 = null; protected List list2 = null; protected List list3 = null; protected List iteratorList = null; public TestObjectGraphIterator(String testName) { super(testName); } public static void main(String[] args) { TestRunner.run(suite()); } public static Test suite() { return new TestSuite(TestObjectGraphIterator.class); } public void setUp() { list1 = new ArrayList(); list1.add("One"); list1.add("Two"); list1.add("Three"); list2 = new ArrayList(); list2.add("Four"); list3 = new ArrayList(); list3.add("Five"); list3.add("Six"); iteratorList = new ArrayList(); iteratorList.add(list1.iterator()); iteratorList.add(list2.iterator()); iteratorList.add(list3.iterator()); } //----------------------------------------------------------------------- public Iterator makeEmptyIterator() { ArrayList list = new ArrayList(); return new ObjectGraphIterator(list.iterator(), null); } public Iterator makeFullIterator() { return new ObjectGraphIterator(iteratorList.iterator(), null); } //----------------------------------------------------------------------- public void testIteratorConstructor_null1() { Iterator it = new ObjectGraphIterator(null); assertEquals(false, it.hasNext()); try { it.next(); fail(); } catch (NoSuchElementException ex) { } try { it.remove(); fail(); } catch (IllegalStateException ex) { } } public void testIteratorConstructor_null_next() { Iterator it = new ObjectGraphIterator(null); try { it.next(); fail(); } catch (NoSuchElementException ex) { } } public void testIteratorConstructor_null_remove() { Iterator it = new ObjectGraphIterator(null); try { it.remove(); fail(); } catch (IllegalStateException ex) { } } //----------------------------------------------------------------------- public void testIteratorConstructorIteration_Empty() { List iteratorList = new ArrayList(); Iterator it = new ObjectGraphIterator(iteratorList.iterator()); assertEquals(false, it.hasNext()); try { it.next(); fail(); } catch (NoSuchElementException ex) { } try { it.remove(); fail(); } catch (IllegalStateException ex) { } } public void testIteratorConstructorIteration_Simple() { List iteratorList = new ArrayList(); iteratorList.add(list1.iterator()); iteratorList.add(list2.iterator()); iteratorList.add(list3.iterator()); Iterator it = new ObjectGraphIterator(iteratorList.iterator()); for (int i = 0; i < 6; i++) { assertEquals(true, it.hasNext()); assertEquals(testArray[i], it.next()); } assertEquals(false, it.hasNext()); try { it.next(); fail(); } catch (NoSuchElementException ex) { } } public void testIteratorConstructorIteration_SimpleNoHasNext() { List iteratorList = new ArrayList(); iteratorList.add(list1.iterator()); iteratorList.add(list2.iterator()); iteratorList.add(list3.iterator()); Iterator it = new ObjectGraphIterator(iteratorList.iterator()); for (int i = 0; i < 6; i++) { assertEquals(testArray[i], it.next()); } try { it.next(); fail(); } catch (NoSuchElementException ex) { } } public void testIteratorConstructorIteration_WithEmptyIterators() { List iteratorList = new ArrayList(); iteratorList.add(IteratorUtils.EMPTY_ITERATOR); iteratorList.add(list1.iterator()); iteratorList.add(IteratorUtils.EMPTY_ITERATOR); iteratorList.add(list2.iterator()); iteratorList.add(IteratorUtils.EMPTY_ITERATOR); iteratorList.add(list3.iterator()); iteratorList.add(IteratorUtils.EMPTY_ITERATOR); Iterator it = new ObjectGraphIterator(iteratorList.iterator()); for (int i = 0; i < 6; i++) { assertEquals(true, it.hasNext()); assertEquals(testArray[i], it.next()); } assertEquals(false, it.hasNext()); try { it.next(); fail(); } catch (NoSuchElementException ex) { } } public void testIteratorConstructorRemove() { List iteratorList = new ArrayList(); iteratorList.add(list1.iterator()); iteratorList.add(list2.iterator()); iteratorList.add(list3.iterator()); Iterator it = new ObjectGraphIterator(iteratorList.iterator()); for (int i = 0; i < 6; i++) { assertEquals(testArray[i], it.next()); it.remove(); } assertEquals(false, it.hasNext()); assertEquals(0, list1.size()); assertEquals(0, list2.size()); assertEquals(0, list3.size()); } //----------------------------------------------------------------------- public void testIteration_IteratorOfIterators() { List iteratorList = new ArrayList(); iteratorList.add(list1.iterator()); iteratorList.add(list2.iterator()); iteratorList.add(list3.iterator()); Iterator it = new ObjectGraphIterator(iteratorList.iterator(), null); for (int i = 0; i < 6; i++) { assertEquals(true, it.hasNext()); assertEquals(testArray[i], it.next()); } assertEquals(false, it.hasNext()); } public void testIteration_IteratorOfIteratorsWithEmptyIterators() { List iteratorList = new ArrayList(); iteratorList.add(IteratorUtils.EMPTY_ITERATOR); iteratorList.add(list1.iterator()); iteratorList.add(IteratorUtils.EMPTY_ITERATOR); iteratorList.add(list2.iterator()); iteratorList.add(IteratorUtils.EMPTY_ITERATOR); iteratorList.add(list3.iterator()); iteratorList.add(IteratorUtils.EMPTY_ITERATOR); Iterator it = new ObjectGraphIterator(iteratorList.iterator(), null); for (int i = 0; i < 6; i++) { assertEquals(true, it.hasNext()); assertEquals(testArray[i], it.next()); } assertEquals(false, it.hasNext()); } //----------------------------------------------------------------------- public void testIteration_RootNull() { Iterator it = new ObjectGraphIterator(null, null); assertEquals(false, it.hasNext()); try { it.next(); fail(); } catch (NoSuchElementException ex) { } try { it.remove(); fail(); } catch (IllegalStateException ex) { } } public void testIteration_RootNoTransformer() { Forest forest = new Forest(); Iterator it = new ObjectGraphIterator(forest, null); assertEquals(true, it.hasNext()); assertSame(forest, it.next()); assertEquals(false, it.hasNext()); try { it.next(); fail(); } catch (NoSuchElementException ex) { } } public void testIteration_Transformed1() { Forest forest = new Forest(); Leaf l1 = forest.addTree().addBranch().addLeaf(); Iterator it = new ObjectGraphIterator(forest, new LeafFinder()); assertEquals(true, it.hasNext()); assertSame(l1, it.next()); assertEquals(false, it.hasNext()); try { it.next(); fail(); } catch (NoSuchElementException ex) { } } public void testIteration_Transformed2() { Forest forest = new Forest(); forest.addTree(); forest.addTree(); forest.addTree(); Branch b1 = forest.getTree(0).addBranch(); Branch b2 = forest.getTree(0).addBranch(); Branch b3 = forest.getTree(2).addBranch(); Branch b4 = forest.getTree(2).addBranch(); Branch b5 = forest.getTree(2).addBranch(); Leaf l1 = b1.addLeaf(); Leaf l2 = b1.addLeaf(); Leaf l3 = b2.addLeaf(); Leaf l4 = b3.addLeaf(); Leaf l5 = b5.addLeaf(); Iterator it = new ObjectGraphIterator(forest, new LeafFinder()); assertEquals(true, it.hasNext()); assertSame(l1, it.next()); assertEquals(true, it.hasNext()); assertSame(l2, it.next()); assertEquals(true, it.hasNext()); assertSame(l3, it.next()); assertEquals(true, it.hasNext()); assertSame(l4, it.next()); assertEquals(true, it.hasNext()); assertSame(l5, it.next()); assertEquals(false, it.hasNext()); try { it.next(); fail(); } catch (NoSuchElementException ex) { } } public void testIteration_Transformed3() { Forest forest = new Forest(); forest.addTree(); forest.addTree(); forest.addTree(); Branch b1 = forest.getTree(1).addBranch(); Branch b2 = forest.getTree(1).addBranch(); Branch b3 = forest.getTree(2).addBranch(); Branch b4 = forest.getTree(2).addBranch(); Branch b5 = forest.getTree(2).addBranch(); Leaf l1 = b1.addLeaf(); Leaf l2 = b1.addLeaf(); Leaf l3 = b2.addLeaf(); Leaf l4 = b3.addLeaf(); Leaf l5 = b4.addLeaf(); Iterator it = new ObjectGraphIterator(forest, new LeafFinder()); assertEquals(true, it.hasNext()); assertSame(l1, it.next()); assertEquals(true, it.hasNext()); assertSame(l2, it.next()); assertEquals(true, it.hasNext()); assertSame(l3, it.next()); assertEquals(true, it.hasNext()); assertSame(l4, it.next()); assertEquals(true, it.hasNext()); assertSame(l5, it.next()); assertEquals(false, it.hasNext()); try { it.next(); fail(); } catch (NoSuchElementException ex) { } } //----------------------------------------------------------------------- static class LeafFinder implements Transformer { public Object transform(Object input) { if (input instanceof Forest) { return ((Forest) input).treeIterator(); } if (input instanceof Tree) { return ((Tree) input).branchIterator(); } if (input instanceof Branch) { return ((Branch) input).leafIterator(); } if (input instanceof Leaf) { return input; } throw new ClassCastException(); } } //----------------------------------------------------------------------- static class Forest { List trees = new ArrayList(); Tree addTree() { trees.add(new Tree()); return getTree(trees.size() - 1); } Tree getTree(int index) { return (Tree) trees.get(index); } Iterator treeIterator() { return trees.iterator(); } } static class Tree { List branches = new ArrayList(); Branch addBranch() { branches.add(new Branch()); return getBranch(branches.size() - 1); } Branch getBranch(int index) { return (Branch) branches.get(index); } Iterator branchIterator() { return branches.iterator(); } } static class Branch { List leaves = new ArrayList(); Leaf addLeaf() { leaves.add(new Leaf()); return getLeaf(leaves.size() - 1); } Leaf getLeaf(int index) { return (Leaf) leaves.get(index); } Iterator leafIterator() { return leaves.iterator(); } } static class Leaf { String colour; String getColour() { return colour; } void setColour(String colour) { this.colour = colour; } } } collections-generic-4.01/src/test/org/apache/commons/collections15/iterators/TestArrayIterator2.java0000644000175000017500000001376510464140764034124 0ustar giovannigiovanni/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.iterators; import junit.framework.Test; import junit.framework.TestSuite; import java.util.Iterator; import java.util.NoSuchElementException; /** * Tests the ArrayIterator with primitive type arrays. * * @author Morgan Delagrange * @author Matt Hall, John Watkinson, James Strachan * @version $Revision: 1.1 $ $Date: 2005/10/11 19:11:58 $ */ public class TestArrayIterator2 extends AbstractTestIterator { protected int[] testArray = {2, 4, 6, 8}; public static Test suite() { return new TestSuite(TestArrayIterator2.class); } public TestArrayIterator2(String testName) { super(testName); } public Iterator makeEmptyIterator() { return new ArrayIterator(new int[0]); } public Iterator makeFullIterator() { return new ArrayIterator(testArray); } /* * We use these makeArrayIterator factory methods instead of * directly calling the constructor so as to allow subclasses * (e.g. TestArrayListIterator2) to use the existing test code. * * @return ArrayIterator */ public ArrayIterator makeArrayIterator() { return (ArrayIterator) makeEmptyIterator(); } public ArrayIterator makeArrayIterator(Object array) { return new ArrayIterator(array); } public ArrayIterator makeArrayIterator(Object array, int index) { return new ArrayIterator(array, index); } public ArrayIterator makeArrayIterator(Object array, int start, int end) { return new ArrayIterator(array, start, end); } public boolean supportsRemove() { return false; } public void testIterator() { Iterator iter = (Iterator) makeFullIterator(); for (int i = 0; i < testArray.length; i++) { Integer testValue = new Integer(testArray[i]); Number iterValue = (Number) iter.next(); assertEquals("Iteration value is correct", testValue, iterValue); } assertTrue("Iterator should now be empty", !iter.hasNext()); try { Object testValue = iter.next(); } catch (Exception e) { assertTrue("NoSuchElementException must be thrown", e.getClass().equals((new NoSuchElementException()).getClass())); } } // proves that an ArrayIterator set with the constructor has the same number of elements // as an ArrayIterator set with setArray(Object) public void testSetArray() { Iterator iter1 = makeArrayIterator(testArray); int count1 = 0; while (iter1.hasNext()) { ++count1; iter1.next(); } assertEquals("the count should be right using the constructor", count1, testArray.length); ArrayIterator iter2 = makeArrayIterator(); iter2.setArray(testArray); int count2 = 0; while (iter2.hasNext()) { ++count2; iter2.next(); } assertEquals("the count should be right using setArray(Object)", count2, testArray.length); } public void testIndexedArray() { Iterator iter = makeArrayIterator(testArray, 2); int count = 0; while (iter.hasNext()) { ++count; iter.next(); } assertEquals("the count should be right using ArrayIterator(Object,2) ", count, testArray.length - 2); iter = makeArrayIterator(testArray, 1, testArray.length - 1); count = 0; while (iter.hasNext()) { ++count; iter.next(); } assertEquals("the count should be right using ArrayIterator(Object,1," + (testArray.length - 1) + ") ", count, testArray.length - 2); try { iter = makeArrayIterator(testArray, -1); fail("new ArrayIterator(Object,-1) should throw an ArrayIndexOutOfBoundsException"); } catch (ArrayIndexOutOfBoundsException aioobe) { // expected } try { iter = makeArrayIterator(testArray, testArray.length + 1); fail("new ArrayIterator(Object,length+1) should throw an ArrayIndexOutOfBoundsException"); } catch (ArrayIndexOutOfBoundsException aioobe) { // expected } try { iter = makeArrayIterator(testArray, 0, -1); fail("new ArrayIterator(Object,0,-1) should throw an ArrayIndexOutOfBoundsException"); } catch (ArrayIndexOutOfBoundsException aioobe) { // expected } try { iter = makeArrayIterator(testArray, 0, testArray.length + 1); fail("new ArrayIterator(Object,0,length+1) should throw an ArrayIndexOutOfBoundsException"); } catch (ArrayIndexOutOfBoundsException aioobe) { // expected } try { iter = makeArrayIterator(testArray, 1, 1); // expected not to fail } catch (IllegalArgumentException iae) { // MODIFIED: an iterator over a zero-length section of array // should be perfectly legal behavior fail("new ArrayIterator(Object,1,1) should NOT throw an IllegalArgumentException"); } try { iter = makeArrayIterator(testArray, testArray.length - 1, testArray.length - 2); fail("new ArrayIterator(Object,length-2,length-1) should throw an IllegalArgumentException"); } catch (IllegalArgumentException iae) { // expected } } } collections-generic-4.01/src/test/org/apache/commons/collections15/iterators/TestFilterIterator.java0000644000175000017500000001244210464140760034174 0ustar giovannigiovanni/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.iterators; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.collections15.Predicate; import java.util.*; /** * Test the filter iterator. * * @author Jan Sorensen * @author Matt Hall, John Watkinson, Ralph Wagner * @version $Revision: 1.1 $ $Date: 2005/10/11 19:11:58 $ */ public class TestFilterIterator extends AbstractTestIterator { /** * Creates new TestFilterIterator */ public TestFilterIterator(String name) { super(name); } private String[] array; private List list; private FilterIterator iterator; /** * Set up instance variables required by this test case. */ public void setUp() { array = new String[]{"a", "b", "c"}; initIterator(); } /** * Tear down instance variables required by this test case. */ public void tearDown() throws Exception { iterator = null; } /** * Return the tests included in this test suite. */ public static Test suite() { return (new TestSuite(TestFilterIterator.class)); } /** * Returns an full iterator wrapped in a * FilterIterator that blocks all the elements * * @return "empty" FilterIterator */ public Iterator makeEmptyIterator() { return makeBlockAllFilter(new ArrayIterator(array)); } /** * Returns an array with elements wrapped in a pass-through * FilterIterator * * @return */ public Iterator makeFullIterator() { array = new String[]{"a", "b", "c"}; list = new ArrayList(Arrays.asList(array)); return makePassThroughFilter(list.iterator()); } public void testRepeatedHasNext() { for (int i = 0; i <= array.length; i++) { assertTrue(iterator.hasNext()); } } public void testRepeatedNext() { for (int i = 0; i < array.length; i++) iterator.next(); verifyNoMoreElements(); } public void testReturnValues() { verifyElementsInPredicate(new String[0]); verifyElementsInPredicate(new String[]{"a"}); verifyElementsInPredicate(new String[]{"b"}); verifyElementsInPredicate(new String[]{"c"}); verifyElementsInPredicate(new String[]{"a", "b"}); verifyElementsInPredicate(new String[]{"a", "c"}); verifyElementsInPredicate(new String[]{"b", "c"}); verifyElementsInPredicate(new String[]{"a", "b", "c"}); } private void verifyNoMoreElements() { assertTrue(!iterator.hasNext()); try { iterator.next(); fail("NoSuchElementException expected"); } catch (NoSuchElementException e) { // success } } private void verifyElementsInPredicate(final String[] elements) { Predicate pred = new Predicate() { public boolean evaluate(Object x) { for (int i = 0; i < elements.length; i++) if (elements[i].equals(x)) return true; return false; } }; initIterator(); iterator.setPredicate(pred); for (int i = 0; i < elements.length; i++) { String s = (String) iterator.next(); assertEquals(elements[i], s); assertTrue(i == elements.length - 1 ? !iterator.hasNext() : iterator.hasNext()); } verifyNoMoreElements(); // test removal initIterator(); iterator.setPredicate(pred); if (iterator.hasNext()) { Object last = iterator.next(); iterator.remove(); assertTrue("Base of FilterIterator still contains removed element.", !list.contains(last)); } } private void initIterator() { iterator = (FilterIterator) makeFullIterator(); } /** * Returns a FilterIterator that does not filter * any of its elements * * @param i the Iterator to "filter" * @return "filtered" iterator */ protected FilterIterator makePassThroughFilter(Iterator i) { Predicate pred = new Predicate() { public boolean evaluate(Object x) { return true; } }; return new FilterIterator(i, pred); } /** * Returns a FilterIterator that blocks * all of its elements * * @param i the Iterator to "filter" * @return "filtered" iterator */ protected FilterIterator makeBlockAllFilter(Iterator i) { Predicate pred = new Predicate() { public boolean evaluate(Object x) { return false; } }; return new FilterIterator(i, pred); } } ././@LongLink0000000000000000000000000000015700000000000011570 Lustar rootrootcollections-generic-4.01/src/test/org/apache/commons/collections15/iterators/TestObjectArrayListIterator2.javacollections-generic-4.01/src/test/org/apache/commons/collections15/iterators/TestObjectArrayListIter0000644000175000017500000000334610464140762034207 0ustar giovannigiovanni/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.iterators; import junit.framework.Test; import junit.framework.TestSuite; import java.util.ListIterator; /** * Tests the ObjectArrayListIterator class. * * @author Matt Hall, John Watkinson, Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 19:11:58 $ */ public class TestObjectArrayListIterator2 extends AbstractTestListIterator { protected String[] testArray = {"One", "Two", "Three"}; public TestObjectArrayListIterator2(String testName) { super(testName); } public static Test suite() { return new TestSuite(TestObjectArrayListIterator2.class); } public ListIterator makeEmptyListIterator() { return new ObjectArrayListIterator(new Object[0]); } public ListIterator makeFullListIterator() { return new ObjectArrayListIterator(testArray); } public ListIterator makeArrayListIterator(Object[] array) { return new ObjectArrayListIterator(array); } public boolean supportsAdd() { return false; } public boolean supportsRemove() { return false; } } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootcollections-generic-4.01/src/test/org/apache/commons/collections15/iterators/AbstractTestIterator.javacollections-generic-4.01/src/test/org/apache/commons/collections15/iterators/AbstractTestIterator.ja0000644000175000017500000001312210464140754034162 0ustar giovannigiovanni/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections15.iterators; import org.apache.commons.collections15.AbstractTestObject; import java.util.Iterator; import java.util.NoSuchElementException; /** * Abstract class for testing the Iterator interface. *

                  * This class provides a framework for testing an implementation of Iterator. * Concrete subclasses must provide the iterator to be tested. * They must also specify certain details of how the iterator operates by * overriding the supportsXxx() methods if necessary. * * @author Matt Hall, John Watkinson, Morgan Delagrange * @author Stephen Colebourne * @version $Revision: 1.1 $ $Date: 2005/10/11 19:11:58 $ * @since Commons Collections 3.0 */ public abstract class AbstractTestIterator extends AbstractTestObject { /** * JUnit constructor. * * @param testName the test class name */ public AbstractTestIterator(String testName) { super(testName); } //----------------------------------------------------------------------- /** * Implement this method to return an iterator over an empty collection. * * @return an empty iterator */ public abstract Iterator makeEmptyIterator(); /** * Implement this method to return an iterator over a collection with elements. * * @return a full iterator */ public abstract Iterator makeFullIterator(); /** * Implements the abstract superclass method to return the full iterator. * * @return a full iterator */ public Object makeObject() { return makeFullIterator(); } /** * Whether or not we are testing an iterator that can be empty. * Default is true. * * @return true if Iterator can be empty */ public boolean supportsEmptyIterator() { return true; } /** * Whether or not we are testing an iterator that can contain elements. * Default is true. * * @return true if Iterator can be full */ public boolean supportsFullIterator() { return true; } /** * Whether or not we are testing an iterator that supports remove(). * Default is true. * * @return true if Iterator supports remove */ public boolean supportsRemove() { return true; } /** * Allows subclasses to add complex cross verification */ public void verify() { // do nothing } //----------------------------------------------------------------------- /** * Test the empty iterator. */ public void testEmptyIterator() { if (supportsEmptyIterator() == false) { return; } Iterator it = makeEmptyIterator(); // hasNext() should return false assertEquals("hasNext() should return false for empty iterators", false, it.hasNext()); // next() should throw a NoSuchElementException try { it.next(); fail("NoSuchElementException must be thrown when Iterator is exhausted"); } catch (NoSuchElementException e) { } verify(); assertNotNull(it.toString()); } /** * Test normal iteration behaviour. */ public void testFullIterator() { if (supportsFullIterator() == false) { return; } Iterator it = makeFullIterator(); // hasNext() must be true (ensure makeFullIterator is correct!) assertEquals("hasNext() should return true for at least one element", true, it.hasNext()); // next() must not throw exception (ensure makeFullIterator is correct!) try { it.next(); } catch (NoSuchElementException e) { fail("Full iterators must have at least one element"); } // iterate through while (it.hasNext()) { it.next(); verify(); } // next() must throw NoSuchElementException now try { it.next(); fail("NoSuchElementException must be thrown when Iterator is exhausted"); } catch (NoSuchElementException e) { } assertNotNull(it.toString()); } /** * Test remove behaviour. */ public void testRemove() { Iterator it = makeFullIterator(); if (supportsRemove() == false) { // check for UnsupportedOperationException if not supported try { it.remove(); } catch (UnsupportedOperationException ex) { } return; } // should throw IllegalStateException before next() called try { it.remove(); fail(); } catch (IllegalStateException ex) { } verify(); // remove after next should be fine it.next(); it.remove(); // should throw IllegalStateException for second remove() try { it.remove(); fail(); } catch (IllegalStateException ex) { } } } collections-generic-4.01/src/conf/0000755000175000017500000000000011664401370017312 5ustar giovannigiovannicollections-generic-4.01/src/conf/MANIFEST.MF0000644000175000017500000000042310464140764020747 0ustar giovannigiovanniManifest-Version: 1.0 Package: @package@ Extension-Name: @name@ Specification-Version: @version@ Specification-Vendor: LarvaLabs, Inc. Specification-Title: @title@ Implementation-Version: @version@ Implementation-Vendor: LarvaLabs, Inc. Implementation-Vendor-Id: collections-generic-4.01/NOTICE.txt0000644000175000017500000000014510464140752017321 0ustar giovannigiovanniThis product includes software developed by The Apache Software Foundation (http://www.apache.org/). collections-generic-4.01/build.properties.sample0000644000175000017500000000127010464140752022274 0ustar giovannigiovanni# Copyright 2001-2004 The Apache Software Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # junit.jar - JUnit 3.8.1 Classpath junit.jar=lib/junit.jar