libcommons-collections3-java.orig/0000755000175000017500000000000011010124150015562 5ustar godgodlibcommons-collections3-java.orig/data/0000755000175000017500000000000010777673536016537 5ustar godgodlibcommons-collections3-java.orig/data/test/0000755000175000017500000000000011010124150017452 5ustar godgodlibcommons-collections3-java.orig/data/test/ArrayStack.emptyCollection.version1.obj0000644000175000017500000000016210777673547027175 0ustar godgodsr)org.apache.commons.collections.ArrayStack/Gxrjava.util.ArrayListxaIsizexpw xlibcommons-collections3-java.orig/data/test/ArrayStack.fullCollection.version1.obj0000644000175000017500000000020310777673551026770 0ustar godgodsr)org.apache.commons.collections.ArrayStack/Gxrjava.util.ArrayListxaIsizexpw t1t3t4q~xlibcommons-collections3-java.orig/data/test/BlockingBuffer.emptyCollection.version3.1.obj0000644000175000017500000000056710777673550030157 0ustar godgodsr4org.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~libcommons-collections3-java.orig/data/test/BlockingBuffer.fullCollection.version3.1.obj0000644000175000017500000000060310777673550027752 0ustar godgodsr4org.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Ϫ fUxpwtAtBtCxq~libcommons-collections3-java.orig/data/test/BooleanComparator.version3.obj0000644000175000017500000000013610777673551025365 0ustar godgodsrsq~?sq~@sq~Asq~Bsq~Csq~Dsq~Esq~Fsq~Gsq~Hsq~Isq~Jsq~Ksq~Lsq~Msq~Nsq~Osq~Psq~Qsq~Rsq~Ssq~Tsq~Usq~Vsq~Wsq~Xsq~Ysq~Zsq~[sq~\sq~]sq~^sq~_sq~`sq~asq~bsq~cxq~dlibcommons-collections3-java.orig/data/test/BoundedFifoBuffer.emptyCollection.version3.1.obj0000644000175000017500000000014510777673550030603 0ustar godgodsr7org.apache.commons.collections.buffer.BoundedFifoBufferMl4Y I maxElementsxpdwxlibcommons-collections3-java.orig/data/test/BoundedFifoBuffer.fullCollection.version3.1.obj0000644000175000017500000000077310777673551030417 0ustar godgodsr7org.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~xlibcommons-collections3-java.orig/data/test/CaseInsensitiveMap.emptyCollection.version3.obj0000644000175000017500000000013110777673550030653 0ustar godgodsr5org.apache.commons.collections.map.CaseInsensitiveMap!nxpw ?@xlibcommons-collections3-java.orig/data/test/CaseInsensitiveMap.fullCollection.version3.obj0000644000175000017500000000052410777673550030465 0ustar godgodsr5org.apache.commons.collections.map.CaseInsensitiveMap!nxpw ?@ tfootfoovtwe'lltwe'llvtseetseevtbaztbazvthellothellovtbartbarvtagaintagainvtkey2tvaluepq~tgoodbyetgoodbyevtkeyptyoutyouvtblahtblahvtgeetgeevttmpttmpvtgollytgollyvtgoshtgoshvtalltallvxlibcommons-collections3-java.orig/data/test/CircularFifoBuffer.emptyCollection.version3.1.obj0000644000175000017500000000025410777673547030776 0ustar godgodsr8org.apache.commons.collections.buffer.CircularFifoBufferEZxr7org.apache.commons.collections.buffer.BoundedFifoBufferMl4Y I maxElementsxpdwxlibcommons-collections3-java.orig/data/test/CircularFifoBuffer.fullCollection.version3.1.obj0000644000175000017500000000110210777673547030573 0ustar godgodsr8org.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~xlibcommons-collections3-java.orig/data/test/ComparableComparator.version2.obj0000644000175000017500000000012410777673547026054 0ustar godgodsr?org.apache.commons.collections.comparators.ComparableComparator%n7xplibcommons-collections3-java.orig/data/test/ComparatorChain.version2.obj0000644000175000017500000000065110777673547025036 0ustar godgodsr: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 uxplibcommons-collections3-java.orig/data/test/CursorableLinkedList.emptyCollection.version1.obj0000644000175000017500000000026310777673547031217 0ustar godgodsr3org.apache.commons.collections.CursorableLinkedListz,zI _modCountL_cursorstLjava/util/List;xpsrjava.util.ArrayListxaIsizexpw xwxlibcommons-collections3-java.orig/data/test/CursorableLinkedList.fullCollection.version1.obj0000644000175000017500000000030410777673547031017 0ustar godgodsr3org.apache.commons.collections.CursorableLinkedListz,zI _modCountL_cursorstLjava/util/List;xpsrjava.util.ArrayListxaIsizexpw xwt1t3t4q~xlibcommons-collections3-java.orig/data/test/DefaultedMap.emptyCollection.version3.2.obj0000644000175000017500000000061310777673547027627 0ustar godgodsr/org.apache.commons.collections.map.DefaultedMapqcLvaluetLjava/lang/Object;xpsr:org.apache.commons.collections.functors.FactoryTransformerb)]LiFactoryt(Lorg/apache/commons/collections/Factory;xpsr7org.apache.commons.collections.functors.ConstantFactory$ m[*L iConstantq~xppsrjava.util.HashMap`F loadFactorI thresholdxp?@ wxxlibcommons-collections3-java.orig/data/test/DefaultedMap.fullCollection.version3.2.obj0000644000175000017500000000120610777673547027432 0ustar godgodsr/org.apache.commons.collections.map.DefaultedMapqcLvaluetLjava/lang/Object;xpsr:org.apache.commons.collections.functors.FactoryTransformerb)]LiFactoryt(Lorg/apache/commons/collections/Factory;xpsr7org.apache.commons.collections.functors.ConstantFactory$ m[*L iConstantq~xppsrjava.util.HashMap`F loadFactorI thresholdxp?@w tfootfoovtwe'lltwe'llvtseetseevtbaztbazvthellothellovtbartbarvtagaintagainvtkey2tvaluepq~tgoodbyetgoodbyevtkeyptyoutyouvtblahtblahvtgeetgeevttmpttmpvtgollytgollyvtgoshtgoshvtalltallvxxlibcommons-collections3-java.orig/data/test/DualHashBidiMap.emptyCollection.version3.obj0000644000175000017500000000023210777673551030043 0ustar godgodsr6org.apache.commons.collections.bidimap.DualHashBidiMap[Pxpsrjava.util.HashMap`F loadFactorI thresholdxp?@wxxlibcommons-collections3-java.orig/data/test/DualHashBidiMap.fullCollection.version3.obj0000644000175000017500000000063110777673547027657 0ustar godgodsr6org.apache.commons.collections.bidimap.DualHashBidiMap[Pxpsrjava.util.HashMap`F loadFactorI thresholdxp?@w tfootfoovtwe'lltwe'llvtseetseevtbaztbazvthellothellovtbartbarvtagaintagainvtkey2tvalueptvalue2tgoodbyetgoodbyevtyoutyouvtkeyptblahtblahvtgeetgeevttmpttmpvtgollytgollyvtgoshtgoshvtalltallvxxlibcommons-collections3-java.orig/data/test/DualTreeBidiMap.emptyCollection.version3.obj0000644000175000017500000000025710777673547030073 0ustar godgodsr6org.apache.commons.collections.bidimap.DualTreeBidiMap[QL comparatortLjava/util/Comparator;xppsrjava.util.TreeMap >-%jL comparatorq~xppwxxlibcommons-collections3-java.orig/data/test/DualTreeBidiMap.emptyCollection.version3.Test2.obj0000644000175000017500000000054110777673551031062 0ustar godgodsr6org.apache.commons.collections.bidimap.DualTreeBidiMap[QL comparatortLjava/util/Comparator;xpsr-%jL comparatorq~xpq~wxxlibcommons-collections3-java.orig/data/test/DualTreeBidiMap.fullCollection.version3.obj0000644000175000017500000000071010777673551027664 0ustar godgodsr6org.apache.commons.collections.bidimap.DualTreeBidiMap[QL comparatortLjava/util/Comparator;xppsrjava.util.TreeMap >-%jL comparatorq~xppwtagaintagainvtalltallvtbartbarvtbaztbazvtblahtblahvtfootfoovtgeetgeevtgollytgollyvtgoodbyetgoodbyevtgoshtgoshvthellothellovtkeyt nonnullvaluetkey2tvaluet nonnullkeytvalue2tseetseevttmpttmpvtwe'lltwe'llvtyoutyouvxxlibcommons-collections3-java.orig/data/test/DualTreeBidiMap.fullCollection.version3.Test2.obj0000644000175000017500000000117210777673551030667 0ustar godgodsr6org.apache.commons.collections.bidimap.DualTreeBidiMap[QL comparatortLjava/util/Comparator;xpsr-%jL comparatorq~xpq~wtyoutyouvtwe'lltwe'llvttmpttmpvtseetseevt nonnullkeytvalue2tkey2tvaluetkeyt nonnullvaluethellothellovtgoshtgoshvtgoodbyetgoodbyevtgollytgollyvtgeetgeevtfootfoovtblahtblahvtbaztbazvtbartbarvtalltallvtagaintagainvxxlibcommons-collections3-java.orig/data/test/FastArrayList.emptyCollection.version1.obj0000644000175000017500000000025510777673547027664 0ustar godgodsr,org.apache.commons.collections.FastArrayList axZfastLlisttLjava/util/ArrayList;xrjava.util.ArrayListxaIsizexpw xsq~w xlibcommons-collections3-java.orig/data/test/FastArrayList.fullCollection.version1.obj0000644000175000017500000000027610777673550027465 0ustar godgodsr,org.apache.commons.collections.FastArrayList axZfastLlisttLjava/util/ArrayList;xrjava.util.ArrayListxaIsizexpw xsq~w t1t3t4q~xlibcommons-collections3-java.orig/data/test/FastHashMap.emptyCollection.version1.obj0000644000175000017500000000031010777673547027263 0ustar godgodsr*org.apache.commons.collections.FastHashMapT&ZfastLmaptLjava/util/HashMap;xrjava.util.HashMap`F loadFactorI thresholdxp?@w xsq~?@w xlibcommons-collections3-java.orig/data/test/FastHashMap.fullCollection.version1.obj0000644000175000017500000000070310777673550027067 0ustar godgodsr*org.apache.commons.collections.FastHashMapT&ZfastLmaptLjava/util/HashMap;xrjava.util.HashMap`F loadFactorI thresholdxp?@w xsq~?@#w/tgollytgollyvtgoodbyetgoodbyevtalltallvtblahtblahvtgeetgeevtyoutyouvtagaintagainvthellothellovtwe'lltwe'llvtbaztbazvtgoshtgoshvtbartbarvtfootfoovtseetseevttmpttmpvtkey2tvaluepq~$tkeypxlibcommons-collections3-java.orig/data/test/FastTreeMap.emptyCollection.version1.obj0000644000175000017500000000027710777673547027313 0ustar godgodsr*org.apache.commons.collections.FastTreeMapx9s]'ZfastLmaptLjava/util/TreeMap;xrjava.util.TreeMap >-%jL comparatortLjava/util/Comparator;xppwxsq~pwxlibcommons-collections3-java.orig/data/test/FastTreeMap.fullCollection.version1.obj0000644000175000017500000000116610777673551027110 0ustar godgodsr*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~&xlibcommons-collections3-java.orig/data/test/FixedSizeList.emptyCollection.version3.1.obj0000644000175000017500000000032110777673547030015 0ustar godgodsr1org.apache.commons.collections.list.FixedSizeList8 ;axrEorg.apache.commons.collections.list.AbstractSerializableListDecorator%B){kxpsrjava.util.ArrayListxaIsizexpw xxlibcommons-collections3-java.orig/data/test/FixedSizeList.fullCollection.version3.1.obj0000644000175000017500000000115010777673551027615 0ustar godgodsr1org.apache.commons.collections.list.FixedSizeList8 ;axrEorg.apache.commons.collections.list.AbstractSerializableListDecorator%B){kxpsrjava.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~xxlibcommons-collections3-java.orig/data/test/FixedSizeMap.emptyCollection.version3.1.obj0000644000175000017500000000022310777673550027612 0ustar godgodsr/org.apache.commons.collections.map.FixedSizeMapggѯtxpsrjava.util.HashMap`F loadFactorI thresholdxp?@wxxlibcommons-collections3-java.orig/data/test/FixedSizeMap.fullCollection.version3.1.obj0000644000175000017500000000061610777673551027425 0ustar godgodsr/org.apache.commons.collections.map.FixedSizeMapggѯtxpsrjava.util.HashMap`F loadFactorI thresholdxp?@w tfootfoovtwe'lltwe'llvtseetseevptvaluetbaztbazvthellothellovtbartbarvtagaintagainvtkey2q~ tgoodbyetgoodbyevtyoutyouvtkeyptblahtblahvtgeetgeevttmpttmpvtgollytgollyvtgoshtgoshvtalltallvxxlibcommons-collections3-java.orig/data/test/FixedSizeSortedMap.emptyCollection.version3.1.obj0000644000175000017500000000023310777673547031002 0ustar godgodsr5org.apache.commons.collections.map.FixedSizeSortedMap+aI?-%jL comparatortLjava/util/Comparator;xppwxxlibcommons-collections3-java.orig/data/test/FixedSizeSortedMap.fullCollection.version3.1.obj0000644000175000017500000000064210777673547030612 0ustar godgodsr5org.apache.commons.collections.map.FixedSizeSortedMap+aI?-%jL comparatortLjava/util/Comparator;xppwtagaintagainvtalltallvtbartbarvtbaztbazvtblahtblahvtfootfoovtgeetgeevtgollytgollyvtgoodbyetgoodbyevtgoshtgoshvthellothellovtkeyptkey2tvaluet nonnullkeyq~tseetseevttmpttmpvtwe'lltwe'llvtyoutyouvxxlibcommons-collections3-java.orig/data/test/Flat3Map.emptyCollection.version3.1.obj0000644000175000017500000000010710777673547026700 0ustar godgodsr+org.apache.commons.collections.map.Flat3Map~qxpwxlibcommons-collections3-java.orig/data/test/Flat3Map.fullCollection.version3.1.obj0000644000175000017500000000050210777673550026475 0ustar godgodsr+org.apache.commons.collections.map.Flat3Map~qxpwtfootfoovtwe'lltwe'llvtseetseevtbaztbazvthellothellovtbartbarvtagaintagainvtkey2tvaluetgoodbyetgoodbyevtkeyptyoutyouvtblahtblahvtgeetgeevttmpttmpvtgollytgollyvtgoshtgoshvtalltallvpq~xlibcommons-collections3-java.orig/data/test/GrowthList.emptyCollection.version3.2.obj0000644000175000017500000000031610777673550027374 0ustar godgodsr.org.apache.commons.collections.list.GrowthList'xrEorg.apache.commons.collections.list.AbstractSerializableListDecorator%B){kxpsrjava.util.ArrayListxaIsizexpw xxlibcommons-collections3-java.orig/data/test/GrowthList.fullCollection.version3.2.obj0000644000175000017500000000114510777673551027202 0ustar godgodsr.org.apache.commons.collections.list.GrowthList'xrEorg.apache.commons.collections.list.AbstractSerializableListDecorator%B){kxpsrjava.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~xxlibcommons-collections3-java.orig/data/test/HashBag.emptyCollection.version3.obj0000644000175000017500000000010610777673547026426 0ustar godgodsr*org.apache.commons.collections.bag.HashBag-%jL comparatortLjava/util/Comparator;xppwxxlibcommons-collections3-java.orig/data/test/LazySortedMap.fullCollection.version3.1.obj0000644000175000017500000000137210777673547027640 0ustar godgodsr0org.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'llvtyoutyouvxxlibcommons-collections3-java.orig/data/test/LinkedMap.emptyCollection.version3.obj0000644000175000017500000000012010777673550026763 0ustar godgodsr,org.apache.commons.collections.map.LinkedMap}І$vGjxpw ?@xlibcommons-collections3-java.orig/data/test/LinkedMap.fullCollection.version3.obj0000644000175000017500000000051310777673547026603 0ustar godgodsr,org.apache.commons.collections.map.LinkedMap}І$vGjxpw ?@ tagaintblahvtalltfoovtbartbarvtbaztbazvtblahttmpvtfootgoshvtgeetgollyvtgollytgeevtgoodbyethellovtgoshtgoodbyevthellotwe'llvtkeytseevtkey2tyouvtseetallvttmptagainvtwe'llptyoutvaluepq~"xlibcommons-collections3-java.orig/data/test/ListOrderedMap.emptyCollection.version3.1.obj0000644000175000017500000000035410777673547030153 0ustar godgodsr1org.apache.commons.collections.map.ListOrderedMap%o53fL insertOrdertLjava/util/List;xpsrjava.util.ArrayListxaIsizexpw xsrjava.util.HashMap`F loadFactorI thresholdxp?@wxxlibcommons-collections3-java.orig/data/test/ListOrderedMap.fullCollection.version3.1.obj0000644000175000017500000000107510777673551027753 0ustar godgodsr1org.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~tfoovxxlibcommons-collections3-java.orig/data/test/ListOrderedSet.emptyCollection.version3.1.obj0000644000175000017500000000043610777673550030164 0ustar godgodsr1org.apache.commons.collections.set.ListOrderedSetӞSLsetOrdertLjava/util/List;xrCorg.apache.commons.collections.set.AbstractSerializableSetDecoratorkxpsrjava.util.HashSetD4xpw ?@xxsrjava.util.ArrayListxaIsizexpwxlibcommons-collections3-java.orig/data/test/ListOrderedSet.fullCollection.version3.1.obj0000644000175000017500000000140510777673550027765 0ustar godgodsr1org.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~ xlibcommons-collections3-java.orig/data/test/LRUMap.emptyCollection.version2.obj0000644000175000017500000000020310777673547026226 0ustar godgodsr%org.apache.commons.collections.LRUMap~̍C xr/org.apache.commons.collections.SequencedHashMap.""& xpwdxlibcommons-collections3-java.orig/data/test/LRUMap.emptyCollection.version3.obj0000644000175000017500000000012110777673550026220 0ustar godgodsr)org.apache.commons.collections.map.LRUMapTxpwd?@xlibcommons-collections3-java.orig/data/test/LRUMap.fullCollection.version2.obj0000644000175000017500000000057610777673550026041 0ustar godgodsr%org.apache.commons.collections.LRUMap~̍C xr/org.apache.commons.collections.SequencedHashMap.""& xpwdtblahtblahvtfootfoovtbartbarvtbaztbazvttmpttmpvtgoshtgoshvtgollytgollyvtgeetgeevthellothellovtgoodbyetgoodbyevtwe'lltwe'llvtseetseevtyoutyouvtalltallvtagaintagainvtkeyptkey2tvaluepq~#xlibcommons-collections3-java.orig/data/test/LRUMap.fullCollection.version3.obj0000644000175000017500000000051410777673551026033 0ustar godgodsr)org.apache.commons.collections.map.LRUMapTxpwd?@tagaintblahvtalltfoovtbartbarvtbaztbazvtblahttmpvtfootgoshvtgeetgollyvtgollytgeevtgoodbyethellovtgoshtgoodbyevthellotwe'llvtkeytseevtkey2tyouvtseetallvttmptagainvtwe'llptyoutvaluepq~"xlibcommons-collections3-java.orig/data/test/MapBackedSet.emptyCollection.version3.1.obj0000644000175000017500000000031310777673547027553 0ustar godgodsr/org.apache.commons.collections.set.MapBackedSet]P"oL dummyValuetLjava/lang/Object;LmaptLjava/util/Map;xppsr,org.apache.commons.collections.map.HashedMap/ FOsxpw ?@xlibcommons-collections3-java.orig/data/test/MapBackedSet.fullCollection.version3.1.obj0000644000175000017500000000115610777673547027365 0ustar godgodsr/org.apache.commons.collections.set.MapBackedSet]P"oL dummyValuetLjava/lang/Object;LmaptLjava/util/Map;xppsr,org.apache.commons.collections.map.HashedMap/ FOsxpw ?@ srjava.lang.Integer⠤8Ivaluexrjava.lang.Number xpptThreepsrjava.lang.ShorthM74`RSvaluexq~ psrjava.lang.ByteN`PBvaluexq~ptEightpsrjava.lang.DoubleJ)kDvaluexq~@psrjava.lang.Floatɢ<Fvaluexq~@pt14psrjava.lang.Long;̏#Jvaluexq~ pppsq~ptSevenptNineptThirteenpt15psq~ ptptOnepxlibcommons-collections3-java.orig/data/test/MultiHashMap.emptyCollection.version2.obj0000644000175000017500000000026710777673550027466 0ustar godgodsr+org.apache.commons.collections.MultiHashMap LmNametLjava/lang/String;xrjava.util.HashMap`F loadFactorI thresholdxp?@w xt MultiMap-26libcommons-collections3-java.orig/data/test/MultiHashMap.fullCollection.version2.obj0000644000175000017500000000141110777673547027270 0ustar godgodsr+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-28libcommons-collections3-java.orig/data/test/MultiKeyMap.emptyCollection.version3.1.obj0000644000175000017500000000031610777673547027474 0ustar godgodsr.org.apache.commons.collections.map.MultiKeyMap/ FOsLmapt6Lorg/apache/commons/collections/map/AbstractHashedMap;xpsr,org.apache.commons.collections.map.HashedMap/ FOsxpw ?@xlibcommons-collections3-java.orig/data/test/MultiKeyMap.fullCollection.version3.1.obj0000644000175000017500000000167010777673547027304 0ustar godgodsr.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~t5Jxlibcommons-collections3-java.orig/data/test/NodeCachingLinkedList.emptyCollection.version3.obj0000644000175000017500000000015410777673547031261 0ustar godgodsr9org.apache.commons.collections.list.NodeCachingLinkedList_޶;? ImaximumCacheSizexpwxlibcommons-collections3-java.orig/data/test/NodeCachingLinkedList.fullCollection.version3.obj0000644000175000017500000000100310777673551031052 0ustar godgodsr9org.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~xlibcommons-collections3-java.orig/data/test/NullComparator.version2.obj10000644000175000017500000000033310777673547025004 0ustar godgodsr9org.apache.commons.collections.comparators.NullComparator8v.Y-Z nullsAreHighLnonNullComparatortLjava/util/Comparator;xpsr?org.apache.commons.collections.comparators.ComparableComparator%n7xplibcommons-collections3-java.orig/data/test/NullComparator.version2.obj20000644000175000017500000000033310777673547025005 0ustar godgodsr9org.apache.commons.collections.comparators.NullComparator8v.Y-Z nullsAreHighLnonNullComparatortLjava/util/Comparator;xpsr?org.apache.commons.collections.comparators.ComparableComparator%n7xplibcommons-collections3-java.orig/data/test/PredicatedBag.emptyCollection.version3.1.obj0000644000175000017500000000066410777673551027752 0ustar godgodsr0org.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.AbstractSerializableCollectionDecoratorV4xpsr*org.apache.commons.collections.bag.HashBagorg.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&,xplibcommons-collections3-java.orig/data/test/PredicatedBuffer.fullCollection.version3.1.obj0000644000175000017500000000060510777673547030276 0ustar godgodsr>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&,xplibcommons-collections3-java.orig/data/test/PredicatedCollection.emptyCollection.version3.1.obj0000644000175000017500000000055110777673550031346 0ustar godgodsr>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&,xplibcommons-collections3-java.orig/data/test/PredicatedCollection.fullCollection.version3.1.obj0000644000175000017500000000060510777673551031153 0ustar godgodsr>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&,xplibcommons-collections3-java.orig/data/test/PredicatedList.emptyCollection.version3.1.obj0000644000175000017500000000065210777673550030170 0ustar godgodsr2org.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&,xplibcommons-collections3-java.orig/data/test/PredicatedList.fullCollection.version3.1.obj0000644000175000017500000000070610777673551027775 0ustar godgodsr2org.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&,xplibcommons-collections3-java.orig/data/test/PredicatedMap.emptyCollection.version3.1.obj0000644000175000017500000000046110777673547027776 0ustar godgodsr0org.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?@wxxlibcommons-collections3-java.orig/data/test/PredicatedMap.fullCollection.version3.1.obj0000644000175000017500000000105410777673547027601 0ustar godgodsr0org.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~ tgoodbyetgoodbyevtyoutyouvtkeyptblahtblahvtgeetgeevttmpttmpvtgollytgollyvtgoshtgoshvtalltallvxxlibcommons-collections3-java.orig/data/test/PredicatedSet.emptyCollection.version3.1.obj0000644000175000017500000000064310777673550030010 0ustar godgodsr0org.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&,xplibcommons-collections3-java.orig/data/test/PredicatedSet.fullCollection.version3.1.obj0000644000175000017500000000067710777673551027624 0ustar godgodsr0org.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&,xplibcommons-collections3-java.orig/data/test/PredicatedSortedBag.emptyCollection.version3.1.obj0000644000175000017500000000077210777673547031140 0ustar godgodsr6org.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&,xplibcommons-collections3-java.orig/data/test/PredicatedSortedBag.fullCollection.version3.1.obj0000644000175000017500000000103010777673550030722 0ustar godgodsr6org.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&,xplibcommons-collections3-java.orig/data/test/PredicatedSortedMap.emptyCollection.version3.1.obj0000644000175000017500000000057010777673550031152 0ustar godgodsr6org.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;xppwxxlibcommons-collections3-java.orig/data/test/PredicatedSortedMap.fullCollection.version3.1.obj0000644000175000017500000000117710777673547030770 0ustar godgodsr6org.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'llvtyoutyouvxxlibcommons-collections3-java.orig/data/test/PredicatedSortedSet.emptyCollection.version3.1.obj0000644000175000017500000000074110777673551031171 0ustar godgodsr6org.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&,xplibcommons-collections3-java.orig/data/test/PredicatedSortedSet.fullCollection.version3.1.obj0000644000175000017500000000152010777673551030771 0ustar godgodsr6org.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[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&,xplibcommons-collections3-java.orig/data/test/PriorityBuffer.emptyCollection.version3.2.obj0000644000175000017500000000034410777673547030250 0ustar godgodsr4org.apache.commons.collections.buffer.PriorityBuffer_ioxZascendingOrderIsizeL comparatortLjava/util/Comparator;[elementst[Ljava/lang/Object;xppur[Ljava.lang.Object;Xs)lxppppppppppppppplibcommons-collections3-java.orig/data/test/PriorityBuffer.fullCollection.version3.2.obj0000644000175000017500000000053210777673547030053 0ustar godgodsr4org.apache.commons.collections.buffer.PriorityBuffer_ioxZascendingOrderIsizeL comparatortLjava/util/Comparator;[elementst[Ljava/lang/Object;xppur[Ljava.lang.Object;Xs)lxpptIft Injurioustcouldtthetdistancetdulltfleshtwaytthoughtt substancetoftmytnottstopq~twereppppppppppplibcommons-collections3-java.orig/data/test/ReferenceIdentityMap.emptyCollection.version3.1.obj0000644000175000017500000000014110777673551031330 0ustar godgodsr7org.apache.commons.collections.map.ReferenceIdentityMapmxpw?@pxlibcommons-collections3-java.orig/data/test/ReferenceIdentityMap.fullCollection.version3.1.obj0000644000175000017500000000056610777673547031154 0ustar godgodsr7org.apache.commons.collections.map.ReferenceIdentityMapmxpw?@ tfootfoovtalltallvtgeetgeevtwe'lltwe'llvtseetseevtkeyt nonnullvaluetyoutyouvtbartbarvtgollytgollyvtgoshtgoshvtkey2tvaluetblahtblahvtgoodbyetgoodbyevttmpttmpvtbaztbazvt nonnullkeyq~thellothellovtagaintagainvpxlibcommons-collections3-java.orig/data/test/ReferenceMap.emptyCollection.version3.1.obj0000644000175000017500000000013110777673550027614 0ustar godgodsr/org.apache.commons.collections.map.ReferenceMapIxpw?@pxlibcommons-collections3-java.orig/data/test/ReferenceMap.fullCollection.version3.1.obj0000644000175000017500000000055610777673550027433 0ustar godgodsr/org.apache.commons.collections.map.ReferenceMapIxpw?@ tfootfoovtwe'lltwe'llvt nonnullkeytvaluetseetseevtbaztbazvthellothellovtbartbarvtagaintagainvtkey2q~tgoodbyetgoodbyevtkeyt nonnullvaluetyoutyouvtblahtblahvtgeetgeevttmpttmpvtgollytgollyvtgoshtgoshvtalltallvpxlibcommons-collections3-java.orig/data/test/ReverseComparator.version2.obj0000644000175000017500000000025710777673547025431 0ustar godgodsr-%jL comparatortLjava/util/Comparator;xppwxxlibcommons-collections3-java.orig/data/test/TransformedSortedMap.fullCollection.version3.1.obj0000644000175000017500000000121010777673547031174 0ustar godgodsr7org.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'llvtyoutyouvxxlibcommons-collections3-java.orig/data/test/TransformedSortedSet.emptyCollection.version3.1.obj0000644000175000017500000000075110777673550031411 0ustar godgodsr7org.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=?wxplibcommons-collections3-java.orig/data/test/TransformedSortedSet.fullCollection.version3.1.obj0000644000175000017500000000153010777673550031211 0ustar godgodsr7org.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=?wxplibcommons-collections3-java.orig/data/test/TreeBag.emptyCollection.version3.obj0000644000175000017500000000010710777673547026443 0ustar godgodsr*org.apache.commons.collections.bag.TreeBagylxppwxlibcommons-collections3-java.orig/data/test/TreeBag.fullCollection.version3.obj0000644000175000017500000000014510777673550026243 0ustar godgodsr*org.apache.commons.collections.bag.TreeBagylxppwtAwtBwtCwxlibcommons-collections3-java.orig/data/test/UnboundedFifoBuffer.emptyCollection.version3.1.obj0000644000175000017500000000012510777673551031145 0ustar godgodsr9org.apache.commons.collections.buffer.UnboundedFifoBufferϪ fUxpwxlibcommons-collections3-java.orig/data/test/UnboundedFifoBuffer.fullCollection.version3.1.obj0000644000175000017500000000075310777673547030765 0ustar godgodsr9org.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~xlibcommons-collections3-java.orig/data/test/UnmodifiableBuffer.emptyCollection.version3.1.obj0000644000175000017500000000023710777673547031025 0ustar godgodsr8org.apache.commons.collections.buffer.UnmodifiableBufferoi?Mxpsr9org.apache.commons.collections.buffer.UnboundedFifoBufferϪ fUxpwxxlibcommons-collections3-java.orig/data/test/UnmodifiableBuffer.fullCollection.version3.1.obj0000644000175000017500000000106510777673550030623 0ustar godgodsr8org.apache.commons.collections.buffer.UnmodifiableBufferoi?Mxpsr9org.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~xxlibcommons-collections3-java.orig/data/test/UnmodifiableCollection.emptyCollection.version3.1.obj0000644000175000017500000000035410777673547031707 0ustar godgodsr@org.apache.commons.collections.collection.UnmodifiableCollection};WxrQorg.apache.commons.collections.collection.AbstractSerializableCollectionDecoratorV4xpsrjava.util.ArrayListxaIsizexpw xxlibcommons-collections3-java.orig/data/test/UnmodifiableCollection.fullCollection.version3.1.obj0000644000175000017500000000120310777673547031505 0ustar godgodsr@org.apache.commons.collections.collection.UnmodifiableCollection};WxrQorg.apache.commons.collections.collection.AbstractSerializableCollectionDecoratorV4xpsrjava.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~xxlibcommons-collections3-java.orig/data/test/UnmodifiableList.emptyCollection.version3.1.obj0000644000175000017500000000032410777673547030524 0ustar godgodsr4org.apache.commons.collections.list.UnmodifiableList[<}xrEorg.apache.commons.collections.list.AbstractSerializableListDecorator%B){kxpsrjava.util.ArrayListxaIsizexpw xxlibcommons-collections3-java.orig/data/test/UnmodifiableList.fullCollection.version3.1.obj0000644000175000017500000000115310777673550030323 0ustar godgodsr4org.apache.commons.collections.list.UnmodifiableList[<}xrEorg.apache.commons.collections.list.AbstractSerializableListDecorator%B){kxpsrjava.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~xxlibcommons-collections3-java.orig/data/test/UnmodifiableMap.emptyCollection.version3.1.obj0000644000175000017500000000022610777673547030327 0ustar godgodsr2org.apache.commons.collections.map.UnmodifiableMap%NDJxpsrjava.util.HashMap`F loadFactorI thresholdxp?@wxxlibcommons-collections3-java.orig/data/test/UnmodifiableMap.fullCollection.version3.1.obj0000644000175000017500000000062110777673551030125 0ustar godgodsr2org.apache.commons.collections.map.UnmodifiableMap%NDJxpsrjava.util.HashMap`F loadFactorI thresholdxp?@w tfootfoovtwe'lltwe'llvtseetseevptvaluetbaztbazvthellothellovtbartbarvtagaintagainvtkey2q~ tgoodbyetgoodbyevtyoutyouvtkeyptblahtblahvtgeetgeevttmpttmpvtgollytgollyvtgoshtgoshvtalltallvxxlibcommons-collections3-java.orig/data/test/UnmodifiableOrderedMap.emptyCollection.version3.1.obj0000644000175000017500000000046710777673550031635 0ustar godgodsr9org.apache.commons.collections.map.UnmodifiableOrderedMappfM%xpsr1org.apache.commons.collections.map.ListOrderedMap%o53fL insertOrdertLjava/util/List;xpsrjava.util.ArrayListxaIsizexpw xsrjava.util.HashMap`F loadFactorI thresholdxp?@wxxxlibcommons-collections3-java.orig/data/test/UnmodifiableOrderedMap.fullCollection.version3.1.obj0000644000175000017500000000121010777673551031425 0ustar godgodsr9org.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~tfoovxxxlibcommons-collections3-java.orig/data/test/UnmodifiableSet.emptyCollection.version3.1.obj0000644000175000017500000000031310777673547030342 0ustar godgodsr2org.apache.commons.collections.set.UnmodifiableSetZ1HaxrCorg.apache.commons.collections.set.AbstractSerializableSetDecoratorkxpsrjava.util.HashSetD4xpw ?@xxlibcommons-collections3-java.orig/data/test/UnmodifiableSet.fullCollection.version3.1.obj0000644000175000017500000000113410777673547030150 0ustar godgodsr2org.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~ ttOnexxlibcommons-collections3-java.orig/data/test/UnmodifiableSortedMap.emptyCollection.version3.1.obj0000644000175000017500000000023610777673551031504 0ustar godgodsr8org.apache.commons.collections.map.UnmodifiableSortedMapPXxpsrjava.util.TreeMap >-%jL comparatortLjava/util/Comparator;xppwxxlibcommons-collections3-java.orig/data/test/UnmodifiableSortedMap.fullCollection.version3.1.obj0000644000175000017500000000064510777673547031321 0ustar godgodsr8org.apache.commons.collections.map.UnmodifiableSortedMapPXxpsrjava.util.TreeMap >-%jL comparatortLjava/util/Comparator;xppwtagaintagainvtalltallvtbartbarvtbaztbazvtblahtblahvtfootfoovtgeetgeevtgollytgollyvtgoodbyetgoodbyevtgoshtgoshvthellothellovtkeyptkey2tvaluet nonnullkeyq~tseetseevttmpttmpvtwe'lltwe'llvtyoutyouvxxlibcommons-collections3-java.orig/data/test/UnmodifiableSortedSet.emptyCollection.version3.1.obj0000644000175000017500000000017010777673547031524 0ustar godgodsr8org.apache.commons.collections.set.UnmodifiableSortedSetzLcxpsrjava.util.TreeSetݘP[xppwxxlibcommons-collections3-java.orig/data/test/UnmodifiableSortedSet.fullCollection.version3.1.obj0000644000175000017500000000074710777673551031335 0ustar godgodsr8org.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~;xxlibcommons-collections3-java.orig/src/0000755000175000017500000000000010777673522016410 5ustar godgodlibcommons-collections3-java.orig/src/assembly/0000755000175000017500000000000011010124150020170 5ustar godgodlibcommons-collections3-java.orig/src/assembly/bin.xml0000644000175000017500000000321510777673304021520 0ustar godgod bin tar.gz zip false LICENSE.txt NOTICE.txt README.txt RELEASE-NOTES.html target *.jar target/site/apidocs apidocs libcommons-collections3-java.orig/src/assembly/src.xml0000644000175000017500000000375310777673304021546 0ustar godgod src tar.gz zip ${project.artifactId}-${project.version}-src build.xml build-testframework.xml checkstyle.xml DEVELOPERS-GUIDE.html LICENSE.txt maven.xml NOTICE.txt pom.xml project.properties project.xml PROPOSAL.html README.txt RELEASE-NOTES.html data src xdocs libcommons-collections3-java.orig/src/conf/0000755000175000017500000000000011010124150017276 5ustar godgodlibcommons-collections3-java.orig/src/conf/MANIFEST.MF0000644000175000017500000000067610777673522021000 0ustar godgodManifest-Version: 1.0 Package: org.apache.commons.collections Extension-Name: commons-collections Specification-Version: @version@ Specification-Vendor: Apache Software Foundation Specification-Title: Commons Collections Implementation-Version: @version@ Implementation-Vendor: Apache Software Foundation Implementation-Title: Commons Collections Implementation-Vendor-Id: org.apache X-Compile-Source-JDK: 1.2 X-Compile-Target-JDK: 1.2libcommons-collections3-java.orig/src/java/0000755000175000017500000000000010777673436017335 5ustar godgodlibcommons-collections3-java.orig/src/java/org/0000755000175000017500000000000010777673436020124 5ustar godgodlibcommons-collections3-java.orig/src/java/org/apache/0000755000175000017500000000000010777673436021345 5ustar godgodlibcommons-collections3-java.orig/src/java/org/apache/commons/0000755000175000017500000000000010777673436023020 5ustar godgodlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/0000755000175000017500000000000011010124151025274 5ustar godgodlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/bag/0000755000175000017500000000000011010124151026025 5ustar godgod././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/bag/AbstractBagDecorator.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/bag/AbstractBagDecorator.j0000644000175000017500000000477010777673505032267 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.bag; import java.util.Set; import org.apache.commons.collections.Bag; import org.apache.commons.collections.collection.AbstractCollectionDecorator; /** * Decorates another Bag to provide additional behaviour. *

* Methods are forwarded directly to the decorated bag. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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(Object object) { return getBag().getCount(object); } public boolean add(Object object, int count) { return getBag().add(object, count); } public boolean remove(Object object, int count) { return getBag().remove(object, count); } public Set uniqueSet() { return getBag().uniqueSet(); } } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/bag/AbstractMapBag.java0000644000175000017500000004455210777673505031554 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.bag; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.lang.reflect.Array; import java.util.Collection; import java.util.ConcurrentModificationException; import java.util.Iterator; import java.util.Map; import java.util.Set; import org.apache.commons.collections.Bag; import org.apache.commons.collections.set.UnmodifiableSet; /** * 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. * * @since Commons Collections 3.0 (previously DefaultMapBag v2.0) * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Chuck Burdick * @author Michael A. Smith * @author Stephen Colebourne * @author Janek Bogucki * @author Steve Clark */ 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(Object object) { MutableInteger count = (MutableInteger) 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()) { Object 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 Object next() { if (parent.modCount != mods) { throw new ConcurrentModificationException(); } if (itemCount == 0) { current = (Map.Entry) entryIterator.next(); itemCount = ((MutableInteger) 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 = (MutableInteger) current.getValue(); if (mut.value > 1) { mut.value--; } else { entryIterator.remove(); } parent.size--; 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(Object 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(Object object, int nCopies) { modCount++; if (nCopies > 0) { MutableInteger mut = (MutableInteger) 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 = (MutableInteger) 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(Object object, int nCopies) { MutableInteger mut = (MutableInteger) map.get(object); if (mut == null) { return false; } if (nCopies <= 0) { return false; } modCount++; if (nCopies < mut.value) { mut.value -= nCopies; 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(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. * @see #retainAll(Collection) * * @param other the bag to retain * @return true if this call changed the collection */ boolean retainAll(Bag other) { boolean result = false; Bag excess = new HashBag(); Iterator i = uniqueSet().iterator(); while (i.hasNext()) { Object 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()) { Object 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()) { Object 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 = (Map.Entry) it.next(); out.writeObject(entry.getKey()); out.writeInt(((MutableInteger) 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++) { Object obj = 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();) { Object 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 = (Map.Entry) it.next(); Object element = entry.getKey(); MutableInteger count = (MutableInteger) entry.getValue(); total += (element == null ? 0 : element.hashCode()) ^ count.value; } 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()) { Object 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(); } } ././@LongLink0000000000000000000000000000015600000000000011567 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/bag/AbstractSortedBagDecorator.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/bag/AbstractSortedBagDecor0000644000175000017500000000452610777673505032331 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.bag; import java.util.Comparator; import org.apache.commons.collections.SortedBag; /** * Decorates another SortedBag to provide additional behaviour. *

* Methods are forwarded directly to the decorated bag. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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 Object first() { return getSortedBag().first(); } public Object last() { return getSortedBag().last(); } public Comparator comparator() { return getSortedBag().comparator(); } } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/bag/HashBag.java0000644000175000017500000000564310777673505030234 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.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; import org.apache.commons.collections.Bag; /** * 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. * * @since Commons Collections 3.0 (previously in main package v2.0) * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Chuck Burdick * @author Stephen Colebourne */ public class HashBag extends AbstractMapBag implements Bag, Serializable { /** Serial version lock */ private 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); } } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/bag/package.html0000644000175000017500000000343210777673505030347 0ustar godgod

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
libcommons-collections3-java.orig/src/java/org/apache/commons/collections/bag/PredicatedBag.java0000644000175000017500000000761310777673505031414 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.bag; import java.util.Set; import org.apache.commons.collections.Bag; import org.apache.commons.collections.Predicate; import org.apache.commons.collections.collection.PredicatedCollection; /** * 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. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne * @author Paul Jack */ 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(Object object, int count) { validate(object); return getBag().add(object, count); } public boolean remove(Object object, int count) { return getBag().remove(object, count); } public Set uniqueSet() { return getBag().uniqueSet(); } public int getCount(Object object) { return getBag().getCount(object); } } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/bag/PredicatedSortedBag.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/bag/PredicatedSortedBag.ja0000644000175000017500000000737110777673505032247 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.bag; import java.util.Comparator; import org.apache.commons.collections.Predicate; import org.apache.commons.collections.SortedBag; /** * 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. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne * @author Paul Jack */ 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 Object first() { return getSortedBag().first(); } public Object last() { return getSortedBag().last(); } public Comparator comparator() { return getSortedBag().comparator(); } } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/bag/SynchronizedBag.java0000644000175000017500000001002210777673505032013 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.bag; import java.util.Set; import org.apache.commons.collections.Bag; import org.apache.commons.collections.collection.SynchronizedCollection; import org.apache.commons.collections.set.SynchronizedSet; /** * 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. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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(Object object, int count) { synchronized (lock) { return getBag().add(object, count); } } public boolean remove(Object 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(Object 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); } } } ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/bag/SynchronizedSortedBag.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/bag/SynchronizedSortedBag.0000644000175000017500000000656510777673505032353 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.bag; import java.util.Comparator; import org.apache.commons.collections.Bag; import org.apache.commons.collections.SortedBag; /** * 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. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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 Object first() { synchronized (lock) { return getSortedBag().first(); } } public synchronized Object last() { synchronized (lock) { return getSortedBag().last(); } } public synchronized Comparator comparator() { synchronized (lock) { return getSortedBag().comparator(); } } } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/bag/TransformedBag.java0000644000175000017500000000746710777673505031643 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.bag; import java.util.Set; import org.apache.commons.collections.Bag; import org.apache.commons.collections.Transformer; import org.apache.commons.collections.collection.TransformedCollection; import org.apache.commons.collections.set.TransformedSet; /** * 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. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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); } } ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/bag/TransformedSortedBag.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/bag/TransformedSortedBag.j0000644000175000017500000000667710777673505032336 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.bag; import java.util.Comparator; import org.apache.commons.collections.SortedBag; import org.apache.commons.collections.Transformer; /** * 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. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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(); } } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/bag/TreeBag.java0000644000175000017500000000757410777673505030255 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.bag; 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; import org.apache.commons.collections.SortedBag; /** * 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. * * @since Commons Collections 3.0 (previously in main package v2.0) * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Chuck Burdick * @author Stephen Colebourne */ public class TreeBag extends AbstractMapBag implements SortedBag, Serializable { /** Serial version lock */ private 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 Object first() { return ((SortedMap) getMap()).firstKey(); } public Object 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); } } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/bag/TypedBag.java0000644000175000017500000000433510777673505030433 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.bag; import org.apache.commons.collections.Bag; import org.apache.commons.collections.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. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne * @author Matthew Hawthorne */ 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(); } } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/bag/TypedSortedBag.java0000644000175000017500000000443210777673505031612 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.bag; import org.apache.commons.collections.SortedBag; import org.apache.commons.collections.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. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne * @author Matthew Hawthorne */ 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(); } } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/bag/UnmodifiableBag.java0000644000175000017500000001113010777673505031733 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.bag; 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; import org.apache.commons.collections.Bag; import org.apache.commons.collections.Unmodifiable; import org.apache.commons.collections.iterators.UnmodifiableIterator; import org.apache.commons.collections.set.UnmodifiableSet; /** * Decorates another Bag to ensure it can't be altered. *

* This class is Serializable from Commons Collections 3.1. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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(Object 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(Object object, int count) { throw new UnsupportedOperationException(); } public boolean remove(Object object, int count) { throw new UnsupportedOperationException(); } public Set uniqueSet() { Set set = getBag().uniqueSet(); return UnmodifiableSet.decorate(set); } } ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/bag/UnmodifiableSortedBag.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/bag/UnmodifiableSortedBag.0000644000175000017500000001122410777673505032256 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.bag; 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; import org.apache.commons.collections.SortedBag; import org.apache.commons.collections.Unmodifiable; import org.apache.commons.collections.iterators.UnmodifiableIterator; import org.apache.commons.collections.set.UnmodifiableSet; /** * Decorates another SortedBag to ensure it can't be altered. *

* This class is Serializable from Commons Collections 3.1. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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(Object 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(Object object, int count) { throw new UnsupportedOperationException(); } public boolean remove(Object object, int count) { throw new UnsupportedOperationException(); } public Set uniqueSet() { Set set = getBag().uniqueSet(); return UnmodifiableSet.decorate(set); } } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/bidimap/0000755000175000017500000000000011010124151026701 5ustar godgod././@LongLink0000000000000000000000000000016000000000000011562 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/bidimap/AbstractBidiMapDecorator.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/bidimap/AbstractBidiMapDec0000644000175000017500000000540710777673501032272 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.bidimap; import org.apache.commons.collections.BidiMap; import org.apache.commons.collections.MapIterator; import org.apache.commons.collections.map.AbstractMapDecorator; /** * 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. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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 Object getKey(Object value) { return getBidiMap().getKey(value); } public Object removeValue(Object value) { return getBidiMap().removeValue(value); } public BidiMap inverseBidiMap() { return getBidiMap().inverseBidiMap(); } } ././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/bidimap/AbstractDualBidiMap.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/bidimap/AbstractDualBidiMa0000644000175000017500000005574710777673501032320 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.bidimap; import java.util.Collection; import java.util.Iterator; import java.util.Map; import java.util.Set; import org.apache.commons.collections.BidiMap; import org.apache.commons.collections.MapIterator; import org.apache.commons.collections.ResettableIterator; import org.apache.commons.collections.collection.AbstractCollectionDecorator; import org.apache.commons.collections.iterators.AbstractIteratorDecorator; import org.apache.commons.collections.keyvalue.AbstractMapEntryDecorator; /** * Abstract BidiMap implemented using two maps. *

* An implementation can be written simply by implementing the * createMap method. * * @see DualHashBidiMap * @see DualTreeBidiMap * @since Commons Collections 3.0 * @version $Id: AbstractDualBidiMap.java 646777 2008-04-10 12:33:15Z niallp $ * * @author Matthew Hawthorne * @author Stephen Colebourne */ public abstract class AbstractDualBidiMap implements BidiMap { /** * Delegate map array. The first map contains standard entries, and the * second contains inverses. */ protected transient final Map[] maps = new Map[2]; /** * 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 Collection 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)}. */ protected AbstractDualBidiMap() { super(); maps[0] = createMap(); maps[1] = 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(); maps[0] = normalMap; maps[1] = 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(); maps[0] = normalMap; maps[1] = 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 Object get(Object key) { return maps[0].get(key); } public int size() { return maps[0].size(); } public boolean isEmpty() { return maps[0].isEmpty(); } public boolean containsKey(Object key) { return maps[0].containsKey(key); } public boolean equals(Object obj) { return maps[0].equals(obj); } public int hashCode() { return maps[0].hashCode(); } public String toString() { return maps[0].toString(); } // BidiMap changes //----------------------------------------------------------------------- public Object put(Object key, Object value) { if (maps[0].containsKey(key)) { maps[1].remove(maps[0].get(key)); } if (maps[1].containsKey(value)) { maps[0].remove(maps[1].get(value)); } final Object obj = maps[0].put(key, value); maps[1].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(entry.getKey(), entry.getValue()); } } public Object remove(Object key) { Object value = null; if (maps[0].containsKey(key)) { value = maps[0].remove(key); maps[1].remove(value); } return value; } public void clear() { maps[0].clear(); maps[1].clear(); } public boolean containsValue(Object value) { return maps[1].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 Object getKey(Object value) { return maps[1].get(value); } public Object removeValue(Object value) { Object key = null; if (maps[1].containsKey(value)) { key = maps[1].remove(value); maps[0].remove(key); } return key; } public BidiMap inverseBidiMap() { if (inverseBidiMap == null) { inverseBidiMap = createBidiMap(maps[1], maps[0], 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 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. * * @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.maps[0].keySet(), parent); } public Iterator iterator() { return parent.createKeySetIterator(super.iterator()); } public boolean contains(Object key) { return parent.maps[0].containsKey(key); } public boolean remove(Object key) { if (parent.maps[0].containsKey(key)) { Object value = parent.maps[0].remove(key); parent.maps[1].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 Object 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 Object 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.maps[0].get(lastKey); super.remove(); parent.maps[1].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.maps[0].values(), parent); } public Iterator iterator() { return parent.createValuesIterator(super.iterator()); } public boolean contains(Object value) { return parent.maps[1].containsKey(value); } public boolean remove(Object value) { if (parent.maps[1].containsKey(value)) { Object key = parent.maps[1].remove(value); parent.maps[0].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 Object 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 Object 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 maps[0] parent.maps[1].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.maps[0].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.maps[0].get(key); if (value == null ? entry.getValue() == null : value.equals(entry.getValue())) { parent.maps[0].remove(key); parent.maps[1].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 Object next() { last = new MapEntry((Map.Entry) 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.maps[1].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 Object setValue(Object value) { Object key = MapEntry.this.getKey(); if (parent.maps[1].containsKey(value) && parent.maps[1].get(value) != key) { throw new IllegalArgumentException("Cannot use setValue() when the object being set is already in the map"); } parent.put(key, value); final Object 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.maps[0].entrySet().iterator(); } public boolean hasNext() { return iterator.hasNext(); } public Object next() { last = (Map.Entry) 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) Object value = last.getValue(); iterator.remove(); parent.maps[1].remove(value); last = null; canRemove = false; } public Object getKey() { if (last == null) { throw new IllegalStateException("Iterator getKey() can only be called after next() and before remove()"); } return last.getKey(); } public Object getValue() { if (last == null) { throw new IllegalStateException("Iterator getValue() can only be called after next() and before remove()"); } return last.getValue(); } public Object setValue(Object value) { if (last == null) { throw new IllegalStateException("Iterator setValue() can only be called after next() and before remove()"); } if (parent.maps[1].containsKey(value) && parent.maps[1].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.maps[0].entrySet().iterator(); last = null; canRemove = false; } public String toString() { if (last != null) { return "MapIterator[" + getKey() + "=" + getValue() + "]"; } else { return "MapIterator[]"; } } } } ././@LongLink0000000000000000000000000000016700000000000011571 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/bidimap/AbstractOrderedBidiMapDecorator.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/bidimap/AbstractOrderedBid0000644000175000017500000000577210777673501032361 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.bidimap; import org.apache.commons.collections.OrderedBidiMap; import org.apache.commons.collections.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. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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 Object firstKey() { return getOrderedBidiMap().firstKey(); } public Object lastKey() { return getOrderedBidiMap().lastKey(); } public Object nextKey(Object key) { return getOrderedBidiMap().nextKey(key); } public Object previousKey(Object key) { return getOrderedBidiMap().previousKey(key); } public OrderedBidiMap inverseOrderedBidiMap() { return getOrderedBidiMap().inverseOrderedBidiMap(); } } ././@LongLink0000000000000000000000000000016600000000000011570 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/bidimap/AbstractSortedBidiMapDecorator.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/bidimap/AbstractSortedBidi0000644000175000017500000000566210777673501032404 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.bidimap; import java.util.Comparator; import java.util.SortedMap; import org.apache.commons.collections.SortedBidiMap; /** * 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. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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(Object fromKey, Object toKey) { return getSortedBidiMap().subMap(fromKey, toKey); } public SortedMap headMap(Object toKey) { return getSortedBidiMap().headMap(toKey); } public SortedMap tailMap(Object fromKey) { return getSortedBidiMap().tailMap(fromKey); } } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/bidimap/DualHashBidiMap.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/bidimap/DualHashBidiMap.ja0000644000175000017500000000751110777673501032173 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.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; import org.apache.commons.collections.BidiMap; /** * 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. * * @since Commons Collections 3.0 * @version $Id: DualHashBidiMap.java 646777 2008-04-10 12:33:15Z niallp $ * * @author Matthew Hawthorne * @author Stephen Colebourne */ 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(maps[0]); } private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); maps[0] = new HashMap(); maps[1] = new HashMap(); Map map = (Map) in.readObject(); putAll(map); } } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/bidimap/DualTreeBidiMap.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/bidimap/DualTreeBidiMap.ja0000644000175000017500000002761310777673501032214 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.bidimap; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.ArrayList; import java.util.Comparator; import java.util.Iterator; import java.util.ListIterator; import java.util.Map; import java.util.SortedMap; import java.util.TreeMap; import org.apache.commons.collections.BidiMap; import org.apache.commons.collections.OrderedBidiMap; import org.apache.commons.collections.OrderedMap; import org.apache.commons.collections.OrderedMapIterator; import org.apache.commons.collections.ResettableIterator; import org.apache.commons.collections.SortedBidiMap; import org.apache.commons.collections.map.AbstractSortedMapDecorator; /** * 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. * * @since Commons Collections 3.0 * @version $Id: DualTreeBidiMap.java 646777 2008-04-10 12:33:15Z niallp $ * * @author Matthew Hawthorne * @author Stephen Colebourne */ 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; } /** * 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 Comparator. * * @param comparator the Comparator */ public DualTreeBidiMap(Comparator comparator) { super(new TreeMap(comparator), new TreeMap(comparator)); 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) maps[0]).comparator(); } public Object firstKey() { return ((SortedMap) maps[0]).firstKey(); } public Object lastKey() { return ((SortedMap) maps[0]).lastKey(); } public Object nextKey(Object key) { if (isEmpty()) { return null; } if (maps[0] instanceof OrderedMap) { return ((OrderedMap) maps[0]).nextKey(key); } SortedMap sm = (SortedMap) maps[0]; Iterator it = sm.tailMap(key).keySet().iterator(); it.next(); if (it.hasNext()) { return it.next(); } return null; } public Object previousKey(Object key) { if (isEmpty()) { return null; } if (maps[0] instanceof OrderedMap) { return ((OrderedMap) maps[0]).previousKey(key); } SortedMap sm = (SortedMap) maps[0]; 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(Object toKey) { SortedMap sub = ((SortedMap) maps[0]).headMap(toKey); return new ViewMap(this, sub); } public SortedMap tailMap(Object fromKey) { SortedMap sub = ((SortedMap) maps[0]).tailMap(fromKey); return new ViewMap(this, sub); } public SortedMap subMap(Object fromKey, Object toKey) { SortedMap sub = ((SortedMap) maps[0]).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 maps[0] as the filtered map, but maps[1] as the full map // this forces containsValue and clear to be overridden super((SortedMap) bidi.createBidiMap(sm, bidi.maps[1], bidi.inverseBidiMap)); this.bidi = (DualTreeBidiMap) map; } public boolean containsValue(Object value) { // override as default implementation jumps to [1] return bidi.maps[0].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(Object toKey) { return new ViewMap(bidi, super.headMap(toKey)); } public SortedMap tailMap(Object fromKey) { return new ViewMap(bidi, super.tailMap(fromKey)); } public SortedMap subMap(Object fromKey, Object 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 Object next() { last = (Map.Entry) iterator.next(); return last.getKey(); } public boolean hasPrevious() { return iterator.hasPrevious(); } public Object previous() { last = (Map.Entry) iterator.previous(); return last.getKey(); } public void remove() { iterator.remove(); parent.remove(last.getKey()); last = null; } public Object getKey() { if (last == null) { throw new IllegalStateException("Iterator getKey() can only be called after next() and before remove()"); } return last.getKey(); } public Object getValue() { if (last == null) { throw new IllegalStateException("Iterator getValue() can only be called after next() and before remove()"); } return last.getValue(); } public Object setValue(Object value) { if (last == null) { throw new IllegalStateException("Iterator setValue() can only be called after next() and before remove()"); } if (parent.maps[1].containsKey(value) && parent.maps[1].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(maps[0]); } private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); maps[0] = new TreeMap(comparator); maps[1] = new TreeMap(comparator); Map map = (Map) in.readObject(); putAll(map); } } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/bidimap/package.html0000644000175000017500000000437410777673501031225 0ustar godgod

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
libcommons-collections3-java.orig/src/java/org/apache/commons/collections/bidimap/TreeBidiMap.java0000644000175000017500000021701310777673501031730 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.bidimap; import java.util.AbstractSet; import java.util.Collection; import java.util.ConcurrentModificationException; import java.util.Iterator; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; import org.apache.commons.collections.BidiMap; import org.apache.commons.collections.KeyValue; import org.apache.commons.collections.MapIterator; import org.apache.commons.collections.OrderedBidiMap; import org.apache.commons.collections.OrderedIterator; import org.apache.commons.collections.OrderedMapIterator; import org.apache.commons.collections.iterators.EmptyOrderedMapIterator; import org.apache.commons.collections.keyvalue.UnmodifiableMapEntry; /** * 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. * * @since Commons Collections 3.0 (previously DoubleOrderedMap v2.0) * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Marc Johnson * @author Stephen Colebourne */ 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 Object get(final Object key) { return doGet((Comparable) key, 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 Object put(final Object key, final Object value) { return doPut((Comparable) key, (Comparable) value, KEY); } /** * 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(entry.getKey(), 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 Object remove(final Object key) { return doRemove((Comparable) key, 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 Object getKey(final Object value) { return doGet((Comparable) value, 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 Object removeValue(final Object value) { return doRemove((Comparable) value, 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 Object 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 Object 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 Object nextKey(Object key) { checkKey(key); Node node = nextGreater(lookup((Comparable) 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 Object previousKey(Object 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 Collection 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 key or get by value * * @param obj the key or value that we're looking for * @param index the KEY or VALUE int * @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 Object doGet(final Comparable obj, final int index) { checkNonNullComparable(obj, index); Node node = lookup(obj, index); return ((node == null) ? null : node.getData(oppositeIndex(index))); } /** * Common put logic, differing only in the return value. * * @param key the key, always the main map key * @param value the value, always the main map value * @param index the KEY or VALUE int, for the return value only * @return the previously mapped value */ private Object doPut(final Comparable key, final Comparable value, final int index) { checkKeyAndValue(key, value); // store previous and remove previous mappings Object prev = (index == KEY ? doGet(key, KEY) : doGet(value, VALUE)); doRemove(key, KEY); doRemove(value, 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.getData(KEY)); 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; } } } } return prev; } /** * Remove by object (remove by key or remove by value) * * @param o the key, or value, that we're looking for * @param index the KEY or VALUE int * * @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 Object doRemove(final Comparable o, final int index) { Node node = lookup(o, index); Object rval = null; if (node != null) { rval = node.getData(oppositeIndex(index)); 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 * @param index the KEY or VALUE int (used to put the right word in the * exception message) * * @throws NullPointerException if o is null * @throws ClassCastException if o is not Comparable */ private static void checkNonNullComparable(final Object o, final int index) { if (o == null) { throw new NullPointerException(dataName[index] + " cannot be null"); } if (!(o instanceof Comparable)) { throw new ClassCastException(dataName[index] + " 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, 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, 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 * @param type the KEY or VALUE int * @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. * * @param type the KEY or VALUE int * @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. * * @param type the KEY or VALUE int * @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, dataType); return (main.lookup((Comparable) obj, dataType) != null); } public boolean remove(final Object obj) { return (main.doRemove((Comparable) obj, dataType) != 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 = TreeBidiMap.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 = TreeBidiMap.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 Comparable[] data; 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 Comparable key, final Comparable value) { super(); data = new Comparable[] { key, 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) { return data[index]; } /** * 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 Object getKey() { return data[KEY]; } /** * Gets the value. * * @return the value corresponding to this entry. */ public Object getValue() { return data[VALUE]; } /** * Optional operation that is not permitted in this implementation * * @param ignored * @return does not return * @throws UnsupportedOperationException always */ public Object setValue(final Object 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 data[KEY].equals(e.getKey()) && data[VALUE].equals(e.getValue()); } /** * @return the hash code value for this map entry. */ public int hashCode() { if (!calculatedHashCode) { hashcodeValue = data[KEY].hashCode() ^ data[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 Object get(final Object key) { return main.getKey(key); } public Object 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 Object firstKey() { if (main.nodeCount == 0) { throw new NoSuchElementException("Map is empty"); } return TreeBidiMap.leastNode(main.rootNode[VALUE], VALUE).getValue(); } public Object lastKey() { if (main.nodeCount == 0) { throw new NoSuchElementException("Map is empty"); } return TreeBidiMap.greatestNode(main.rootNode[VALUE], VALUE).getValue(); } public Object nextKey(Object key) { checkKey(key); Node node = main.nextGreater(main.lookup((Comparable) key, VALUE), VALUE); return (node == null ? null : node.getValue()); } public Object previousKey(Object key) { checkKey(key); Node node = main.nextSmaller(main.lookup((Comparable) key, VALUE), VALUE); return (node == null ? null : node.getValue()); } public Object put(final Object key, final Object value) { return main.doPut((Comparable) value, (Comparable) key, VALUE); } public void putAll(Map map) { Iterator it = map.entrySet().iterator(); while (it.hasNext()) { Map.Entry entry = (Map.Entry) it.next(); put(entry.getKey(), entry.getValue()); } } public Object remove(final Object key) { return main.removeValue(key); } public Object 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 Collection 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); } } } ././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/bidimap/UnmodifiableBidiMap.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/bidimap/UnmodifiableBidiMa0000644000175000017500000001004110777673501032317 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.bidimap; import java.util.Collection; import java.util.Map; import java.util.Set; import org.apache.commons.collections.BidiMap; import org.apache.commons.collections.MapIterator; import org.apache.commons.collections.Unmodifiable; import org.apache.commons.collections.collection.UnmodifiableCollection; import org.apache.commons.collections.iterators.UnmodifiableMapIterator; import org.apache.commons.collections.map.UnmodifiableEntrySet; import org.apache.commons.collections.set.UnmodifiableSet; /** * Decorates another BidiMap to ensure it can't be altered. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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 Object put(Object key, Object value) { throw new UnsupportedOperationException(); } public void putAll(Map mapToCopy) { throw new UnsupportedOperationException(); } public Object 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 Object 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; } } ././@LongLink0000000000000000000000000000016200000000000011564 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/bidimap/UnmodifiableOrderedBidiMap.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/bidimap/UnmodifiableOrdere0000644000175000017500000001105410777673501032417 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.bidimap; import java.util.Collection; import java.util.Map; import java.util.Set; import org.apache.commons.collections.BidiMap; import org.apache.commons.collections.MapIterator; import org.apache.commons.collections.OrderedBidiMap; import org.apache.commons.collections.OrderedMapIterator; import org.apache.commons.collections.Unmodifiable; import org.apache.commons.collections.collection.UnmodifiableCollection; import org.apache.commons.collections.iterators.UnmodifiableOrderedMapIterator; import org.apache.commons.collections.map.UnmodifiableEntrySet; import org.apache.commons.collections.set.UnmodifiableSet; /** * Decorates another OrderedBidiMap to ensure it can't be altered. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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 Object put(Object key, Object value) { throw new UnsupportedOperationException(); } public void putAll(Map mapToCopy) { throw new UnsupportedOperationException(); } public Object 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 Object 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; } } ././@LongLink0000000000000000000000000000016100000000000011563 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/bidimap/UnmodifiableSortedBidiMap.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/bidimap/UnmodifiableSorted0000644000175000017500000001256210777673501032444 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.bidimap; import java.util.Collection; import java.util.Map; import java.util.Set; import java.util.SortedMap; import org.apache.commons.collections.BidiMap; import org.apache.commons.collections.MapIterator; import org.apache.commons.collections.OrderedBidiMap; import org.apache.commons.collections.OrderedMapIterator; import org.apache.commons.collections.SortedBidiMap; import org.apache.commons.collections.Unmodifiable; import org.apache.commons.collections.collection.UnmodifiableCollection; import org.apache.commons.collections.iterators.UnmodifiableOrderedMapIterator; import org.apache.commons.collections.map.UnmodifiableEntrySet; import org.apache.commons.collections.map.UnmodifiableSortedMap; import org.apache.commons.collections.set.UnmodifiableSet; /** * Decorates another SortedBidiMap to ensure it can't be altered. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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 Object put(Object key, Object value) { throw new UnsupportedOperationException(); } public void putAll(Map mapToCopy) { throw new UnsupportedOperationException(); } public Object 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 Object 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(Object fromKey, Object toKey) { SortedMap sm = getSortedBidiMap().subMap(fromKey, toKey); return UnmodifiableSortedMap.decorate(sm); } public SortedMap headMap(Object toKey) { SortedMap sm = getSortedBidiMap().headMap(toKey); return UnmodifiableSortedMap.decorate(sm); } public SortedMap tailMap(Object fromKey) { SortedMap sm = getSortedBidiMap().tailMap(fromKey); return UnmodifiableSortedMap.decorate(sm); } } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/buffer/0000755000175000017500000000000011010124151026545 5ustar godgod././@LongLink0000000000000000000000000000015600000000000011567 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/buffer/AbstractBufferDecorator.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/buffer/AbstractBufferDecor0000644000175000017500000000443310777673440032403 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.buffer; import org.apache.commons.collections.Buffer; import org.apache.commons.collections.collection.AbstractCollectionDecorator; /** * Decorates another Buffer to provide additional behaviour. *

* Methods are forwarded directly to the decorated buffer. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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 Object get() { return getBuffer().get(); } public Object remove() { return getBuffer().remove(); } } ././@LongLink0000000000000000000000000000014500000000000011565 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/buffer/BlockingBuffer.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/buffer/BlockingBuffer.java0000644000175000017500000002210710777673440032331 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.buffer; import java.io.PrintWriter; import java.io.StringWriter; import java.util.Collection; import org.apache.commons.collections.Buffer; import org.apache.commons.collections.BufferUnderflowException; /** * 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. * This class contains an extra field in 3.2, however the serialization * specification will handle this gracefully. * * @author Stephen Colebourne * @author Janek Bogucki * @author Phil Steitz * @author James Carman * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * @since Commons Collections 3.0 */ public class BlockingBuffer extends SynchronizedBuffer { /** Serialization version. */ private static final long serialVersionUID = 1719328905017860541L; /** The timeout value in milliseconds. */ private final long timeout; /** * 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); } /** * Factory method to create a blocking buffer with a timeout value. * * @param buffer the buffer to decorate, must not be null * @param timeoutMillis the timeout value in milliseconds, zero or less for no timeout * @return a new blocking buffer * @throws IllegalArgumentException if the buffer is null * @since Commons Collections 3.2 */ public static Buffer decorate(Buffer buffer, long timeoutMillis) { return new BlockingBuffer(buffer, timeoutMillis); } //----------------------------------------------------------------------- /** * 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); this.timeout = 0; } /** * Constructor that wraps (not copies). * * @param buffer the buffer to decorate, must not be null * @param timeoutMillis the timeout value in milliseconds, zero or less for no timeout * @throws IllegalArgumentException if the buffer is null * @since Commons Collections 3.2 */ protected BlockingBuffer(Buffer buffer, long timeoutMillis) { super(buffer); this.timeout = (timeoutMillis < 0 ? 0 : timeoutMillis); } //----------------------------------------------------------------------- public boolean add(Object o) { synchronized (lock) { boolean result = collection.add(o); lock.notifyAll(); return result; } } public boolean addAll(Collection c) { synchronized (lock) { boolean result = collection.addAll(c); lock.notifyAll(); return result; } } /** * Gets the next value from the buffer, waiting until an object is * added if the buffer is empty. This method uses the default timeout * set in the constructor. * * @throws BufferUnderflowException if an interrupt is received */ public Object get() { synchronized (lock) { while (collection.isEmpty()) { try { if (timeout <= 0) { lock.wait(); } else { return get(timeout); } } catch (InterruptedException e) { PrintWriter out = new PrintWriter(new StringWriter()); e.printStackTrace(out); throw new BufferUnderflowException("Caused by InterruptedException: " + out.toString()); } } return getBuffer().get(); } } /** * Gets the next value from the buffer, waiting until an object is * added for up to the specified timeout value if the buffer is empty. * * @param timeout the timeout value in milliseconds * @throws BufferUnderflowException if an interrupt is received * @throws BufferUnderflowException if the timeout expires * @since Commons Collections 3.2 */ public Object get(final long timeout) { synchronized (lock) { final long expiration = System.currentTimeMillis() + timeout; long timeLeft = expiration - System.currentTimeMillis(); while (timeLeft > 0 && collection.isEmpty()) { try { lock.wait(timeLeft); timeLeft = expiration - System.currentTimeMillis(); } catch(InterruptedException e) { PrintWriter out = new PrintWriter(new StringWriter()); e.printStackTrace(out); throw new BufferUnderflowException("Caused by InterruptedException: " + out.toString()); } } if (collection.isEmpty()) { throw new BufferUnderflowException("Timeout expired"); } return getBuffer().get(); } } /** * Removes the next value from the buffer, waiting until an object is * added if the buffer is empty. This method uses the default timeout * set in the constructor. * * @throws BufferUnderflowException if an interrupt is received */ public Object remove() { synchronized (lock) { while (collection.isEmpty()) { try { if (timeout <= 0) { lock.wait(); } else { return remove(timeout); } } catch (InterruptedException e) { PrintWriter out = new PrintWriter(new StringWriter()); e.printStackTrace(out); throw new BufferUnderflowException("Caused by InterruptedException: " + out.toString()); } } return getBuffer().remove(); } } /** * Removes the next value from the buffer, waiting until an object is * added for up to the specified timeout value if the buffer is empty. * * @param timeout the timeout value in milliseconds * @throws BufferUnderflowException if an interrupt is received * @throws BufferUnderflowException if the timeout expires * @since Commons Collections 3.2 */ public Object remove(final long timeout) { synchronized (lock) { final long expiration = System.currentTimeMillis() + timeout; long timeLeft = expiration - System.currentTimeMillis(); while (timeLeft > 0 && collection.isEmpty()) { try { lock.wait(timeLeft); timeLeft = expiration - System.currentTimeMillis(); } catch(InterruptedException e) { PrintWriter out = new PrintWriter(new StringWriter()); e.printStackTrace(out); throw new BufferUnderflowException("Caused by InterruptedException: " + out.toString()); } } if (collection.isEmpty()) { throw new BufferUnderflowException("Timeout expired"); } return getBuffer().remove(); } } } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/buffer/BoundedBuffer.java0000644000175000017500000001642010777673440032162 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.buffer; import java.io.PrintWriter; import java.io.StringWriter; import java.util.Collection; import java.util.Iterator; import org.apache.commons.collections.BoundedCollection; import org.apache.commons.collections.Buffer; import org.apache.commons.collections.BufferOverflowException; import org.apache.commons.collections.BufferUnderflowException; import org.apache.commons.collections.iterators.AbstractIteratorDecorator; /** * Decorates another Buffer to ensure a fixed maximum size. *

* Note: This class should only be used if you need to add bounded * behaviour to another buffer. If you just want a bounded buffer then * you should use {@link BoundedFifoBuffer} or {@link CircularFifoBuffer}. *

* The decoration methods allow you to specify a timeout value. * This alters the behaviour of the add methods when the buffer is full. * Normally, when the buffer is full, the add method will throw an exception. * With a timeout, the add methods will wait for up to the timeout period * to try and add the elements. * * @author James Carman * @author Stephen Colebourne * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * @since Commons Collections 3.2 */ public class BoundedBuffer extends SynchronizedBuffer implements BoundedCollection { /** The serialization version. */ private static final long serialVersionUID = 1536432911093974264L; /** The maximum size. */ private final int maximumSize; /** The timeout milliseconds. */ private final long timeout; /** * Factory method to create a bounded buffer. *

* When the buffer is full, it will immediately throw a * BufferOverflowException on calling add(). * * @param buffer the buffer to decorate, must not be null * @param maximumSize the maximum size, must be size one or greater * @return a new bounded buffer * @throws IllegalArgumentException if the buffer is null * @throws IllegalArgumentException if the maximum size is zero or less */ public static BoundedBuffer decorate(Buffer buffer, int maximumSize) { return new BoundedBuffer(buffer, maximumSize, 0L); } /** * Factory method to create a bounded buffer that blocks for a maximum * amount of time. * * @param buffer the buffer to decorate, must not be null * @param maximumSize the maximum size, must be size one or greater * @param timeout the maximum amount of time to wait in milliseconds * @return a new bounded buffer * @throws IllegalArgumentException if the buffer is null * @throws IllegalArgumentException if the maximum size is zero or less */ public static BoundedBuffer decorate(Buffer buffer, int maximumSize, long timeout) { return new BoundedBuffer(buffer, maximumSize, timeout); } //----------------------------------------------------------------------- /** * Constructor that wraps (not copies) another buffer, making it bounded * waiting only up to a maximum amount of time. * * @param buffer the buffer to wrap, must not be null * @param maximumSize the maximum size, must be size one or greater * @param timeout the maximum amount of time to wait * @throws IllegalArgumentException if the buffer is null * @throws IllegalArgumentException if the maximum size is zero or less */ protected BoundedBuffer(Buffer buffer, int maximumSize, long timeout) { super(buffer); if (maximumSize < 1) { throw new IllegalArgumentException(); } this.maximumSize = maximumSize; this.timeout = timeout; } //----------------------------------------------------------------------- public Object remove() { synchronized (lock) { Object returnValue = getBuffer().remove(); lock.notifyAll(); return returnValue; } } public boolean add(Object o) { synchronized (lock) { timeoutWait(1); return getBuffer().add(o); } } public boolean addAll(final Collection c) { synchronized (lock) { timeoutWait(c.size()); return getBuffer().addAll(c); } } public Iterator iterator() { return new NotifyingIterator(collection.iterator()); } private void timeoutWait(final int nAdditions) { // method synchronized by callers if (nAdditions > maximumSize) { throw new BufferOverflowException( "Buffer size cannot exceed " + maximumSize); } if (timeout <= 0) { // no wait period (immediate timeout) if (getBuffer().size() + nAdditions > maximumSize) { throw new BufferOverflowException( "Buffer size cannot exceed " + maximumSize); } return; } final long expiration = System.currentTimeMillis() + timeout; long timeLeft = expiration - System.currentTimeMillis(); while (timeLeft > 0 && getBuffer().size() + nAdditions > maximumSize) { try { lock.wait(timeLeft); timeLeft = expiration - System.currentTimeMillis(); } catch (InterruptedException ex) { PrintWriter out = new PrintWriter(new StringWriter()); ex.printStackTrace(out); throw new BufferUnderflowException( "Caused by InterruptedException: " + out.toString()); } } if (getBuffer().size() + nAdditions > maximumSize) { throw new BufferOverflowException("Timeout expired"); } } public boolean isFull() { // size() is synchronized return (size() == maxSize()); } public int maxSize() { return maximumSize; } //----------------------------------------------------------------------- /** * BoundedBuffer iterator. */ private class NotifyingIterator extends AbstractIteratorDecorator { public NotifyingIterator(Iterator it) { super(it); } public void remove() { synchronized (lock) { iterator.remove(); lock.notifyAll(); } } } } ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/buffer/BoundedFifoBuffer.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/buffer/BoundedFifoBuffer.j0000644000175000017500000002737110777673440032305 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.buffer; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.AbstractCollection; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.NoSuchElementException; import org.apache.commons.collections.BoundedCollection; import org.apache.commons.collections.Buffer; import org.apache.commons.collections.BufferOverflowException; import org.apache.commons.collections.BufferUnderflowException; /** * The BoundedFifoBuffer is a very efficient implementation of * Buffer that is of a fixed size. *

* 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. * * @since Commons Collections 3.0 (previously in main package v2.1) * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Avalon * @author Berin Loritsch * @author Paul Jack * @author Stephen Colebourne * @author Herve Quiroz */ public class BoundedFifoBuffer extends AbstractCollection implements Buffer, BoundedCollection, Serializable { /** Serialization version */ private static final long serialVersionUID = 5603722811189451017L; /** Underlying storage array */ private transient Object[] elements; /** Array index of first (oldest) buffer element */ private transient int start = 0; /** * Index mod maxElements of the array position following the last buffer * element. Buffer elements start at elements[start] and "wrap around" * elements[maxElements-1], ending at elements[decrement(end)]. * For example, elements = {c,a,b}, start=1, end=1 corresponds to * the buffer [a,b,c]. */ private transient int end = 0; /** Flag to indicate if the buffer is currently full. */ private transient boolean full = false; /** Capacity of the buffer */ 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 = 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 = new Object[maxElements]; int size = in.readInt(); for (int i = 0; i < size; i++) { elements[i] = 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(Object 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 Object 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 Object remove() { if (isEmpty()) { throw new BufferUnderflowException("The buffer is already empty"); } Object 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 Object 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; } int pos = lastReturnedIndex + 1; if (start < lastReturnedIndex && pos < end) { // shift in one part System.arraycopy(elements, pos, elements, lastReturnedIndex, end - pos); } else { // Other elements require us to shift the subsequent elements while (pos != end) { if (pos >= maxElements) { elements[pos - 1] = elements[0]; pos = 0; } else { elements[decrement(pos)] = elements[pos]; pos = increment(pos); } } } lastReturnedIndex = -1; end = decrement(end); elements[end] = null; full = false; index = decrement(index); } }; } } ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/buffer/CircularFifoBuffer.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/buffer/CircularFifoBuffer.0000644000175000017500000000652510777673440032315 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.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. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stefano Fornari * @author Stephen Colebourne */ 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(Object element) { if (isFull()) { remove(); } return super.add(element); } } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/buffer/package.html0000644000175000017500000000365410777673440031073 0ustar godgod

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
././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/buffer/PredicatedBuffer.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/buffer/PredicatedBuffer.ja0000644000175000017500000000734710777673440032327 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.buffer; import org.apache.commons.collections.Buffer; import org.apache.commons.collections.Predicate; import org.apache.commons.collections.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. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne * @author Paul Jack */ 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 Object get() { return getBuffer().get(); } public Object remove() { return getBuffer().remove(); } } ././@LongLink0000000000000000000000000000014500000000000011565 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/buffer/PriorityBuffer.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/buffer/PriorityBuffer.java0000644000175000017500000004372710777673440032435 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.buffer; import java.io.Serializable; import java.util.AbstractCollection; import java.util.Comparator; import java.util.Iterator; import java.util.NoSuchElementException; import org.apache.commons.collections.Buffer; import org.apache.commons.collections.BufferUnderflowException; /** * 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.collections.BufferUtils#synchronizedBuffer(Buffer)} or * {@link org.apache.commons.collections.buffer.SynchronizedBuffer#decorate(Buffer)} * to provide synchronized access to a PriorityBuffer: *

 * Buffer heap = SynchronizedBuffer.decorate(new PriorityBuffer());
 * 
*

* This class is Serializable from Commons Collections 3.2. * * @since Commons Collections 3.0 (previously BinaryHeap v1.0) * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Peter Donald * @author Ram Chidambaram * @author Michael A. Smith * @author Paul Jack * @author Stephen Colebourne * @author Steve Phelps */ public class PriorityBuffer extends AbstractCollection implements Buffer, Serializable { /** Serialization lock. */ private static final long serialVersionUID = 6891186490470027896L; /** * The default capacity for the buffer. */ private static final int DEFAULT_CAPACITY = 13; /** * The elements in this buffer. */ protected Object[] 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 = 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 = 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(Object 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 Object 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 Object remove() { final Object 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 Object 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 Object 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; Object 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 Object 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; Object 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 Object 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(Object a, Object 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 Object[] array = 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 Object 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 collections. * * @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(); } } ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/buffer/SynchronizedBuffer.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/buffer/SynchronizedBuffer.0000644000175000017500000000623210777673440032417 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.buffer; import org.apache.commons.collections.Buffer; import org.apache.commons.collections.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. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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 Object get() { synchronized (lock) { return getBuffer().get(); } } public Object remove() { synchronized (lock) { return getBuffer().remove(); } } } ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/buffer/TransformedBuffer.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/buffer/TransformedBuffer.j0000644000175000017500000000660710777673440032404 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.buffer; import org.apache.commons.collections.Buffer; import org.apache.commons.collections.Transformer; import org.apache.commons.collections.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. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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(); } } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/buffer/TypedBuffer.java0000644000175000017500000000442510777673440031671 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.buffer; import org.apache.commons.collections.Buffer; import org.apache.commons.collections.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. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne * @author Matthew Hawthorne */ 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(); } } ././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/buffer/UnboundedFifoBuffer.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/buffer/UnboundedFifoBuffer0000644000175000017500000002322110777673440032406 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.buffer; 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; import org.apache.commons.collections.Buffer; import org.apache.commons.collections.BufferUnderflowException; /** * UnboundedFifoBuffer is a very efficient implementation of * Buffer that can grow to any size. * 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. * * @since Commons Collections 3.0 (previously in main package v2.1) * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Avalon * @author Federico Barbieri * @author Berin Loritsch * @author Paul Jack * @author Stephen Colebourne * @author Andreas Schlosser * @author Thomas Knych * @author Jordan Krey */ public class UnboundedFifoBuffer extends AbstractCollection implements Buffer, Serializable { // invariant: buffer.length > size() // ie.buffer always has at least one empty entry /** Serialization vesrion */ private static final long serialVersionUID = -3482960336579541419L; /** The array of objects in the buffer. */ protected transient Object[] 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 = 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 = new Object[size + 1]; for (int i = 0; i < size; i++) { buffer[i] = 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 Object obj) { if (obj == null) { throw new NullPointerException("Attempted to add null object to buffer"); } if (size() + 1 >= buffer.length) { // copy contents to a new buffer array Object[] tmp = new Object[((buffer.length - 1) * 2) + 1]; int j = 0; // move head to element zero in the new array for (int i = head; i != tail;) { tmp[j] = buffer[i]; buffer[i] = null; j++; i = increment(i); } buffer = tmp; head = 0; tail = j; } buffer[tail] = obj; tail = increment(tail); return true; } /** * Returns the next object in the buffer. * * @return the next object in the buffer * @throws BufferUnderflowException if this buffer is empty */ public Object 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 Object remove() { if (isEmpty()) { throw new BufferUnderflowException("The buffer is already empty"); } Object element = buffer[head]; if (element != null) { buffer[head] = null; head = increment(head); } 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 Object 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 = increment(lastReturnedIndex); while (i != tail) { buffer[decrement(i)] = buffer[i]; i = increment(i); } lastReturnedIndex = -1; tail = decrement(tail); buffer[tail] = null; index = decrement(index); } }; } } ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/buffer/UnmodifiableBuffer.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/buffer/UnmodifiableBuffer.0000644000175000017500000001051710777673440032337 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.buffer; 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 org.apache.commons.collections.Buffer; import org.apache.commons.collections.Unmodifiable; import org.apache.commons.collections.iterators.UnmodifiableIterator; /** * Decorates another Buffer to ensure it can't be altered. *

* This class is Serializable from Commons Collections 3.1. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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(Object 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 Object remove() { throw new UnsupportedOperationException(); } } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/collection/0000755000175000017500000000000011010124151027427 5ustar godgod././@LongLink0000000000000000000000000000016600000000000011570 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/collection/AbstractCollectionDecorator.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/collection/AbstractCollect0000644000175000017500000001065210777673506032467 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.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. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne * @author Paul Jack */ 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(Object 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 collection.toArray(); } public Object[] toArray(Object[] object) { return 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(); } } ././@LongLink0000000000000000000000000000020200000000000011557 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/collection/AbstractSerializableCollectionDecorator.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/collection/AbstractSeriali0000644000175000017500000000445210777673506032473 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.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 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(); } } ././@LongLink0000000000000000000000000000015600000000000011567 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/collection/CompositeCollection.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/collection/CompositeCollec0000644000175000017500000004027410777673506032505 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.collection; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import org.apache.commons.collections.iterators.EmptyIterator; import org.apache.commons.collections.iterators.IteratorChain; import org.apache.commons.collections.list.UnmodifiableList; /** * Decorates a collection of other collections 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. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Brian McCallister * @author Stephen Colebourne * @author Phil Steitz */ 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 collections. * * @param colls an array of collections 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 collections 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 collections */ 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 collections in this composite. *

* This implementation uses an IteratorChain. * * @return an IteratorChain instance which supports * remove(). Iteration occurs over contained collections 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 Object[] toArray() { final Object[] result = new Object[this.size()]; int i = 0; for (Iterator it = this.iterator(); it.hasNext(); i++) { result[i] = 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 Object[] toArray(Object[] array) { int size = this.size(); Object[] result = null; if (array.length >= size) { result = array; } else { result = (Object[]) 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++] = 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(Object 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 collections 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 collections to this composite. * * @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 collections being decorated. * * @return Unmodifiable collection of all collections 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); } } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/collection/package.html0000644000175000017500000000311510777673506031750 0ustar godgod

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
././@LongLink0000000000000000000000000000015700000000000011570 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/collection/PredicatedCollection.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/collection/PredicatedColle0000644000175000017500000001244510777673506032443 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.collection; import java.util.Collection; import java.util.Iterator; import org.apache.commons.collections.Predicate; /** * 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. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne * @author Paul Jack */ 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(Object 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(Object 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); } } ././@LongLink0000000000000000000000000000016100000000000011563 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/collection/SynchronizedCollection.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/collection/SynchronizedCol0000644000175000017500000001344210777673506032533 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.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. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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(Object 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 Object[] toArray(Object[] 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();
        }
    }

}
././@LongLink0000000000000000000000000000016000000000000011562 Lustar  rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/collection/TransformedCollection.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/collection/TransformedColl0000644000175000017500000001061110777673506032507 0ustar  godgod/*
 *  Licensed to the Apache Software Foundation (ASF) under one or more
 *  contributor license agreements.  See the NOTICE file distributed with
 *  this work for additional information regarding copyright ownership.
 *  The ASF licenses this file to You under the Apache License, Version 2.0
 *  (the "License"); you may not use this file except in compliance with
 *  the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package org.apache.commons.collections.collection;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.collections.Transformer;

/**
 * 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. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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 Object transform(Object 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) { object = transform(object); return getCollection().add(object); } public boolean addAll(Collection coll) { coll = transform(coll); return getCollection().addAll(coll); } } ././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/collection/TypedCollection.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/collection/TypedCollection0000644000175000017500000000446010777673506032517 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.collection; import java.util.Collection; import org.apache.commons.collections.functors.InstanceofPredicate; /** * 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. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne * @author Matthew Hawthorne */ 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(); } } ././@LongLink0000000000000000000000000000017000000000000011563 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/collection/UnmodifiableBoundedCollection.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/collection/UnmodifiableBou0000644000175000017500000001233310777673506032460 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.collection; import java.util.Collection; import java.util.Iterator; import org.apache.commons.collections.BoundedCollection; import org.apache.commons.collections.iterators.UnmodifiableIterator; /** * 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. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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(Object 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(); } } ././@LongLink0000000000000000000000000000016100000000000011563 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/collection/UnmodifiableCollection.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/collection/UnmodifiableCol0000644000175000017500000000645510777673506032460 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.collection; import java.util.Collection; import java.util.Iterator; import org.apache.commons.collections.Unmodifiable; import org.apache.commons.collections.iterators.UnmodifiableIterator; /** * Decorates another Collection to ensure it can't be altered. *

* This class is Serializable from Commons Collections 3.1. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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(Object 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(); } } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/comparators/0000755000175000017500000000000011010124151027626 5ustar godgod././@LongLink0000000000000000000000000000015500000000000011566 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/comparators/BooleanComparator.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/comparators/BooleanCompara0000644000175000017500000001752010777673505032477 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.comparators; import java.io.Serializable; import java.util.Comparator; /** * A {@link Comparator} for {@link Boolean} objects that can sort either * true or false first. *

* @see #getTrueFirstComparator() * @see #getFalseFirstComparator() * @see #getBooleanComparator(boolean) * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Rodney Waldhoff */ 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 arbitrary Objects. * When both arguments are Boolean, this method is equivalent to * {@link #compare(Boolean,Boolean) compare((Boolean)obj1,(Boolean)obj2)}. * When either argument is not a Boolean, this methods throws * a {@link ClassCastException}. * * @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 ClassCastException when either argument is not Boolean */ public int compare(Object obj1, Object obj2) { return compare((Boolean)obj1, (Boolean)obj2); } /** * Compares two non-null Boolean objects * according to the value of {@link #sortsTrueFirst()}. * * @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 value of {@link #sortsTrueFirst()} 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; } } ././@LongLink0000000000000000000000000000016000000000000011562 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/comparators/ComparableComparator.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/comparators/ComparableComp0000644000175000017500000001174610777673505032505 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.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. * * @since Commons Collections 2.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Henri Yandell * * @see java.util.Collections#reverseOrder() */ 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 ComparableComparator 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(Object obj1, Object obj2) { return ((Comparable)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()))); } } ././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/comparators/ComparatorChain.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/comparators/ComparatorChai0000644000175000017500000003032710777673505032511 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.comparators; import java.io.Serializable; import java.util.ArrayList; import java.util.BitSet; import java.util.Comparator; import java.util.Iterator; import java.util.List; /** *

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.

* * @since Commons Collections 2.0 * @author Morgan Delagrange * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ */ 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 * @exception 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 * @exception UnsupportedOperationException * if the ComparatorChain does not contain at least one * Comparator */ public int compare(Object o1, Object 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 = (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; } } } ././@LongLink0000000000000000000000000000016000000000000011562 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/comparators/FixedOrderComparator.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/comparators/FixedOrderComp0000644000175000017500000002471710777673505032475 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.comparators; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; /** * 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. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author David Leppik * @author Stephen Colebourne * @author Janek Bogucki */ 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(Object[] 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(Object obj) { checkLocked(); Object 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(Object existingObj, Object newObj) { checkLocked(); Integer position = (Integer) map.get(existingObj); if (position == null) { throw new IllegalArgumentException(existingObj + " not known to " + this); } Object 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(Object obj1, Object 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); } } } ././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/comparators/NullComparator.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/comparators/NullComparator0000644000175000017500000001622410777673505032557 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.comparators; import java.io.Serializable; import java.util.Comparator; /** * A Comparator that will compare nulls to be either lower or higher than * other objects. * * @since Commons Collections 2.0 * @version $Revision: 647116 $ $Date: 2008-04-11 12:23:08 +0100 (Fri, 11 Apr 2008) $ * * @author Michael A. Smith */ 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 {@link ComparableComparator} is * used. **/ public NullComparator() { this(ComparableComparator.getInstance(), true); } /** * 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 * * @exception 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 {@link ComparableComparator} is * used. * * @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. **/ public NullComparator(boolean nullsAreHigh) { this(ComparableComparator.getInstance(), nullsAreHigh); } /** * 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. * * @exception 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(Object o1, Object 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))); } } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/comparators/package.html0000644000175000017500000000227510777673505032154 0ustar godgod

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. ././@LongLink0000000000000000000000000000015500000000000011566 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/comparators/ReverseComparator.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/comparators/ReverseCompara0000644000175000017500000001103710777673505032530 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.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. * * @since Commons Collections 2.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Henri Yandell * @author Michael A. Smith * * @see java.util.Collections#reverseOrder() */ 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 compares objects based on the inverse of their * natural ordering. Using this Constructor will create a ReverseComparator * that is functionally identical to the Comparator returned by * java.util.Collections.reverseOrder(). * * @see java.util.Collections#reverseOrder() */ public ReverseComparator() { this(null); } /** * Creates a comparator that inverts the comparison * of the given comparator. If you pass in null, * the ReverseComparator defaults to reversing the * natural order, as per * {@link java.util.Collections#reverseOrder()}. * * @param comparator Comparator to reverse */ public ReverseComparator(Comparator comparator) { if(comparator != null) { this.comparator = comparator; } else { this.comparator = ComparableComparator.getInstance(); } } //----------------------------------------------------------------------- /** * 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(Object obj1, Object 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; } } } ././@LongLink0000000000000000000000000000016200000000000011564 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/comparators/TransformingComparator.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/comparators/TransformingCo0000644000175000017500000000614210777673505032546 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.comparators; import java.util.Comparator; import org.apache.commons.collections.Transformer; /** * 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. * * @since Commons Collections 2.0 (?) * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @see org.apache.commons.collections.Transformer * @see org.apache.commons.collections.comparators.ComparableComparator */ 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 a * {@link ComparableComparator ComparableComparator}. * * @param transformer what will transform the arguments to compare */ public TransformingComparator(Transformer transformer) { this(transformer, new ComparableComparator()); } /** * 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(Object obj1, Object obj2) { Object value1 = this.transformer.transform(obj1); Object value2 = this.transformer.transform(obj2); return this.decorated.compare(value1, value2); } } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/functors/0000755000175000017500000000000011010124151027137 5ustar godgod././@LongLink0000000000000000000000000000014500000000000011565 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/functors/AllPredicate.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/functors/AllPredicate.java0000644000175000017500000001057010777673477032405 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.functors; import java.io.Serializable; import java.util.Collection; import org.apache.commons.collections.Predicate; /** * Predicate implementation that returns true if all the * predicates return true. * If the array of predicates is empty, then this predicate returns true. *

* NOTE: In versions prior to 3.2 an array size of zero or one * threw an exception. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne * @author Matt Benson */ public final class AllPredicate implements Predicate, PredicateDecorator, Serializable { /** Serial version UID */ private static final long serialVersionUID = -3094696765038308799L; /** The array of predicates to call */ private final Predicate[] iPredicates; /** * Factory to create the predicate. *

* If the array is size zero, the predicate always returns true. * If the array is size one, then that predicate is returned. * * @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 */ public static Predicate getInstance(Predicate[] predicates) { FunctorUtils.validate(predicates); if (predicates.length == 0) { return TruePredicate.INSTANCE; } if (predicates.length == 1) { return predicates[0]; } predicates = FunctorUtils.copy(predicates); return new AllPredicate(predicates); } /** * Factory to create the predicate. *

* If the collection is size zero, the predicate always returns true. * If the collection is size one, then that predicate is returned. * * @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 */ public static Predicate getInstance(Collection predicates) { Predicate[] preds = FunctorUtils.validate(predicates); if (preds.length == 0) { return TruePredicate.INSTANCE; } if (preds.length == 1) { return preds[0]; } 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(Object 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; } } ././@LongLink0000000000000000000000000000014500000000000011565 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/functors/AndPredicate.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/functors/AndPredicate.java0000644000175000017500000000630010777673477032373 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.functors; import java.io.Serializable; import org.apache.commons.collections.Predicate; /** * Predicate implementation that returns true if both the predicates return true. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ public final class AndPredicate implements Predicate, PredicateDecorator, Serializable { /** Serial version UID */ private 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(Object 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}; } } ././@LongLink0000000000000000000000000000014500000000000011565 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/functors/AnyPredicate.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/functors/AnyPredicate.java0000644000175000017500000001052310777673476032421 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.functors; import java.io.Serializable; import java.util.Collection; import org.apache.commons.collections.Predicate; /** * Predicate implementation that returns true if any of the * predicates return true. * If the array of predicates is empty, then this predicate returns false. *

* NOTE: In versions prior to 3.2 an array size of zero or one * threw an exception. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne * @author Matt Benson */ public final class AnyPredicate implements Predicate, PredicateDecorator, Serializable { /** Serial version UID */ private static final long serialVersionUID = 7429999530934647542L; /** The array of predicates to call */ private final Predicate[] iPredicates; /** * Factory to create the predicate. *

* If the array is size zero, the predicate always returns false. * If the array is size one, then that predicate is returned. * * @param predicates the predicates to check, cloned, not null * @return the any predicate * @throws IllegalArgumentException if the predicates array is null * @throws IllegalArgumentException if any predicate in the array is null */ public static Predicate getInstance(Predicate[] predicates) { FunctorUtils.validate(predicates); if (predicates.length == 0) { return FalsePredicate.INSTANCE; } if (predicates.length == 1) { return predicates[0]; } return new AnyPredicate(FunctorUtils.copy(predicates)); } /** * Factory to create the predicate. *

* If the collection is size zero, the predicate always returns false. * If the collection is size one, then that predicate is returned. * * @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 */ public static Predicate getInstance(Collection predicates) { Predicate[] preds = FunctorUtils.validate(predicates); if (preds.length == 0) { return FalsePredicate.INSTANCE; } if (preds.length == 1) { return preds[0]; } 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(Object 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; } } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/functors/ChainedClosure.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/functors/ChainedClosure.ja0000644000175000017500000001122510777673476032412 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.functors; import java.io.Serializable; import java.util.Collection; import java.util.Iterator; import org.apache.commons.collections.Closure; /** * Closure implementation that chains the specified closures together. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ public class ChainedClosure implements Closure, Serializable { /** Serial version UID */ private 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(Object 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; } } ././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/functors/ChainedTransformer.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/functors/ChainedTransforme0000644000175000017500000001232310777673476032525 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.functors; import java.io.Serializable; import java.util.Collection; import java.util.Iterator; import org.apache.commons.collections.Transformer; /** * 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. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ public class ChainedTransformer implements Transformer, Serializable { /** Serial version UID */ private 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++] = (Transformer) 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 Object transform(Object object) { for (int i = 0; i < iTransformers.length; i++) { object = iTransformers[i].transform(object); } return object; } /** * Gets the transformers, do not modify the array. * @return the transformers * @since Commons Collections 3.1 */ public Transformer[] getTransformers() { return iTransformers; } } ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/functors/CloneTransformer.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/functors/CloneTransformer.0000644000175000017500000000437010777673476032475 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.functors; import java.io.Serializable; import org.apache.commons.collections.Transformer; /** * Transformer implementation that returns a clone of the input object. *

* Clone is performed using PrototypeFactory.getInstance(input).create(). * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ public class CloneTransformer implements Transformer, Serializable { /** Serial version UID */ private 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 Object transform(Object input) { if (input == null) { return null; } return PrototypeFactory.getInstance(input).create(); } } ././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/functors/ClosureTransformer.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/functors/ClosureTransforme0000644000175000017500000000536710777673476032620 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.functors; import java.io.Serializable; import org.apache.commons.collections.Closure; import org.apache.commons.collections.Transformer; /** * Transformer implementation that calls a Closure using the input object * and then returns the input. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ public class ClosureTransformer implements Transformer, Serializable { /** Serial version UID */ private 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 Object transform(Object input) { iClosure.execute(input); return input; } /** * Gets the closure. * * @return the closure * @since Commons Collections 3.1 */ public Closure getClosure() { return iClosure; } } ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/functors/ConstantFactory.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/functors/ConstantFactory.j0000644000175000017500000000547410777673476032513 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.functors; import java.io.Serializable; import org.apache.commons.collections.Factory; /** * 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. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ public class ConstantFactory implements Factory, Serializable { /** Serial version UID */ private 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 Object 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(Object 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(Object constantToReturn) { super(); iConstant = constantToReturn; } /** * Always return constant. * * @return the stored constant value */ public Object create() { return iConstant; } /** * Gets the constant. * * @return the constant * @since Commons Collections 3.1 */ public Object getConstant() { return iConstant; } } ././@LongLink0000000000000000000000000000015400000000000011565 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/functors/ConstantTransformer.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/functors/ConstantTransform0000644000175000017500000000573310777673476032625 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.functors; import java.io.Serializable; import org.apache.commons.collections.Transformer; /** * 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. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ public class ConstantTransformer implements Transformer, Serializable { /** Serial version UID */ private 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 Object 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(Object 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(Object 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 Object transform(Object input) { return iConstant; } /** * Gets the constant. * * @return the constant * @since Commons Collections 3.1 */ public Object getConstant() { return iConstant; } } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/functors/EqualPredicate.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/functors/EqualPredicate.ja0000644000175000017500000000522210777673476032412 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.functors; import java.io.Serializable; import org.apache.commons.collections.Predicate; /** * Predicate implementation that returns true if the input is the same object * as the one stored in this predicate by equals. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ public final class EqualPredicate implements Predicate, Serializable { /** Serial version UID */ private static final long serialVersionUID = 5633766978029907089L; /** The value to compare to */ private final Object 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(Object 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(Object 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(Object object) { return (iValue.equals(object)); } /** * Gets the value. * * @return the value * @since Commons Collections 3.1 */ public Object getValue() { return iValue; } } ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/functors/ExceptionClosure.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/functors/ExceptionClosure.0000644000175000017500000000415010777673476032501 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.functors; import java.io.Serializable; import org.apache.commons.collections.Closure; import org.apache.commons.collections.FunctorException; /** * Closure implementation that always throws an exception. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ public final class ExceptionClosure implements Closure, Serializable { /** Serial version UID */ private 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(Object input) { throw new FunctorException("ExceptionClosure invoked"); } } ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/functors/ExceptionFactory.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/functors/ExceptionFactory.0000644000175000017500000000411510777673477032476 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.functors; import java.io.Serializable; import org.apache.commons.collections.Factory; import org.apache.commons.collections.FunctorException; /** * Factory implementation that always throws an exception. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ public final class ExceptionFactory implements Factory, Serializable { /** Serial version UID */ private 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 Object create() { throw new FunctorException("ExceptionFactory invoked"); } } ././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/functors/ExceptionPredicate.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/functors/ExceptionPredicat0000644000175000017500000000426310777673476032547 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.functors; import java.io.Serializable; import org.apache.commons.collections.FunctorException; import org.apache.commons.collections.Predicate; /** * Predicate implementation that always throws an exception. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ public final class ExceptionPredicate implements Predicate, Serializable { /** Serial version UID */ private 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(Object object) { throw new FunctorException("ExceptionPredicate invoked"); } } ././@LongLink0000000000000000000000000000015500000000000011566 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/functors/ExceptionTransformer.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/functors/ExceptionTransfor0000644000175000017500000000430610777673476032610 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.functors; import java.io.Serializable; import org.apache.commons.collections.FunctorException; import org.apache.commons.collections.Transformer; /** * Transformer implementation that always throws an exception. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ public final class ExceptionTransformer implements Transformer, Serializable { /** Serial version UID */ private 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 Object transform(Object input) { throw new FunctorException("ExceptionTransformer invoked"); } } ././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/functors/FactoryTransformer.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/functors/FactoryTransforme0000644000175000017500000000537310777673476032610 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.functors; import java.io.Serializable; import org.apache.commons.collections.Factory; import org.apache.commons.collections.Transformer; /** * Transformer implementation that calls a Factory and returns the result. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ public class FactoryTransformer implements Transformer, Serializable { /** Serial version UID */ private 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 Object transform(Object input) { return iFactory.create(); } /** * Gets the factory. * * @return the factory * @since Commons Collections 3.1 */ public Factory getFactory() { return iFactory; } } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/functors/FalsePredicate.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/functors/FalsePredicate.ja0000644000175000017500000000402110777673476032371 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.functors; import java.io.Serializable; import org.apache.commons.collections.Predicate; /** * Predicate implementation that always returns false. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ public final class FalsePredicate implements Predicate, Serializable { /** Serial version UID */ private 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(Object object) { return false; } } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/functors/ForClosure.java0000644000175000017500000000622610777673476032141 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.functors; import java.io.Serializable; import org.apache.commons.collections.Closure; /** * Closure implementation that calls another closure n times, like a for loop. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ public class ForClosure implements Closure, Serializable { /** Serial version UID */ private 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(Object 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; } } ././@LongLink0000000000000000000000000000014500000000000011565 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/functors/FunctorUtils.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/functors/FunctorUtils.java0000644000175000017500000001221310777673476032510 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.functors; import java.util.Collection; import java.util.Iterator; import org.apache.commons.collections.Closure; import org.apache.commons.collections.Predicate; import org.apache.commons.collections.Transformer; /** * Internal utilities for functors. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne * @author Matt Benson */ 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 * @return predicate array */ static Predicate[] validate(Collection predicates) { if (predicates == null) { throw new IllegalArgumentException("The predicate collection must not be null"); } // 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] = (Predicate) 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"); } } } } ././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/functors/IdentityPredicate.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/functors/IdentityPredicate0000644000175000017500000000526610777673476032553 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.functors; import java.io.Serializable; import org.apache.commons.collections.Predicate; /** * Predicate implementation that returns true if the input is the same object * as the one stored in this predicate. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ public final class IdentityPredicate implements Predicate, Serializable { /** Serial version UID */ private static final long serialVersionUID = -89901658494523293L; /** The value to compare to */ private final Object 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(Object 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(Object 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(Object object) { return (iValue == object); } /** * Gets the value. * * @return the value * @since Commons Collections 3.1 */ public Object getValue() { return iValue; } } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/functors/IfClosure.java0000644000175000017500000001206710777673477031752 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.functors; import java.io.Serializable; import org.apache.commons.collections.Closure; import org.apache.commons.collections.Predicate; /** * Closure implementation acts as an if statement calling one or other closure * based on a predicate. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne * @author Matt Benson */ public class IfClosure implements Closure, Serializable { /** Serial version UID */ private 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. *

* This factory creates a closure that performs no action when * the predicate is false. * * @param predicate predicate to switch on * @param trueClosure closure used if true * @return the if closure * @throws IllegalArgumentException if either argument is null * @since Commons Collections 3.2 */ public static Closure getInstance(Predicate predicate, Closure trueClosure) { return getInstance(predicate, trueClosure, NOPClosure.INSTANCE); } /** * 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. *

* This constructor creates a closure that performs no action when * the predicate is false. * * @param predicate predicate to switch on, not null * @param trueClosure closure used if true, not null * @since Commons Collections 3.2 */ public IfClosure(Predicate predicate, Closure trueClosure) { this(predicate, trueClosure, NOPClosure.INSTANCE); } /** * 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(Object 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; } } ././@LongLink0000000000000000000000000000015400000000000011565 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/functors/InstanceofPredicate.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/functors/InstanceofPredica0000644000175000017500000000530610777673476032515 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.functors; import java.io.Serializable; import org.apache.commons.collections.Predicate; /** * Predicate implementation that returns true if the input is an instanceof * the type stored in this predicate. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ public final class InstanceofPredicate implements Predicate, Serializable { /** Serial version UID */ private 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; } } ././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/functors/InstantiateFactory.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/functors/InstantiateFactor0000644000175000017500000001215110777673476032552 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.functors; import java.io.Serializable; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import org.apache.commons.collections.Factory; import org.apache.commons.collections.FunctorException; /** * Factory implementation that creates a new object instance by reflection. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ public class InstantiateFactory implements Factory, Serializable { /** The serial version */ private 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 Object create() { // needed for post-serialization if (iConstructor == null) { findConstructor(); } try { return 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); } } } ././@LongLink0000000000000000000000000000015700000000000011570 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/functors/InstantiateTransformer.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/functors/InstantiateTransf0000644000175000017500000001110710777673476032571 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.functors; import java.io.Serializable; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import org.apache.commons.collections.FunctorException; import org.apache.commons.collections.Transformer; /** * Transformer implementation that creates a new object instance by reflection. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ public class InstantiateTransformer implements Transformer, Serializable { /** The serial version */ private static final long serialVersionUID = 3786388740793356347L; /** Singleton instance that uses the no arg constructor */ public static final Transformer 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 Transformer 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(Object input) { try { if (input instanceof Class == false) { throw new FunctorException( "InstantiateTransformer: Input object was not an instanceof Class, it was a " + (input == null ? "null object" : input.getClass().getName())); } 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); } } } ././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/functors/InvokerTransformer.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/functors/InvokerTransforme0000644000175000017500000001247210777673476032614 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.functors; import java.io.Serializable; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import org.apache.commons.collections.FunctorException; import org.apache.commons.collections.Transformer; /** * Transformer implementation that creates a new object instance by reflection. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ public class InvokerTransformer implements Transformer, Serializable { /** The serial version */ private 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); } } } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/functors/MapTransformer.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/functors/MapTransformer.ja0000644000175000017500000000523210777673476032463 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.functors; import java.io.Serializable; import java.util.Map; import org.apache.commons.collections.Transformer; /** * Transformer implementation that returns the value held in a specified map * using the input parameter as a key. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ public final class MapTransformer implements Transformer, Serializable { /** Serial version UID */ private 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 Object transform(Object input) { return iMap.get(input); } /** * Gets the map to lookup in. * * @return the map * @since Commons Collections 3.1 */ public Map getMap() { return iMap; } } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/functors/NonePredicate.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/functors/NonePredicate.jav0000644000175000017500000001013010777673476032422 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.functors; import java.io.Serializable; import java.util.Collection; import org.apache.commons.collections.Predicate; /** * Predicate implementation that returns true if none of the * predicates return true. * If the array of predicates is empty, then this predicate returns true. *

* NOTE: In versions prior to 3.2 an array size of zero or one * threw an exception. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne * @author Matt Benson */ public final class NonePredicate implements Predicate, PredicateDecorator, Serializable { /** Serial version UID */ private static final long serialVersionUID = 2007613066565892961L; /** The array of predicates to call */ private final Predicate[] iPredicates; /** * Factory to create the predicate. *

* If the array is size zero, the predicate always returns true. * * @param predicates the predicates to check, cloned, not null * @return the any predicate * @throws IllegalArgumentException if the predicates array is null * @throws IllegalArgumentException if any predicate in the array is null */ public static Predicate getInstance(Predicate[] predicates) { FunctorUtils.validate(predicates); if (predicates.length == 0) { return TruePredicate.INSTANCE; } predicates = FunctorUtils.copy(predicates); return new NonePredicate(predicates); } /** * Factory to create the predicate. *

* If the collection is size zero, the predicate always returns true. * * @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 */ public static Predicate getInstance(Collection predicates) { Predicate[] preds = FunctorUtils.validate(predicates); if (preds.length == 0) { return TruePredicate.INSTANCE; } 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(Object 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; } } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/functors/NOPClosure.java0000644000175000017500000000362610777673477032051 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.functors; import java.io.Serializable; import org.apache.commons.collections.Closure; /** * Closure implementation that does nothing. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ public class NOPClosure implements Closure, Serializable { /** Serial version UID */ private 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(Object input) { // do nothing } } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/functors/NOPTransformer.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/functors/NOPTransformer.ja0000644000175000017500000000404610777673476032404 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.functors; import java.io.Serializable; import org.apache.commons.collections.Transformer; /** * Transformer implementation that does nothing. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ public class NOPTransformer implements Transformer, Serializable { /** Serial version UID */ private 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 Object transform(Object input) { return input; } } ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/functors/NotNullPredicate.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/functors/NotNullPredicate.0000644000175000017500000000412710777673476032426 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.functors; import java.io.Serializable; import org.apache.commons.collections.Predicate; /** * Predicate implementation that returns true if the input is not null. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ public final class NotNullPredicate implements Predicate, Serializable { /** Serial version UID */ private 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(Object object) { return (object != null); } } ././@LongLink0000000000000000000000000000014500000000000011565 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/functors/NotPredicate.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/functors/NotPredicate.java0000644000175000017500000000545210777673476032437 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.functors; import java.io.Serializable; import org.apache.commons.collections.Predicate; /** * Predicate implementation that returns the opposite of the decorated predicate. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ public final class NotPredicate implements Predicate, PredicateDecorator, Serializable { /** Serial version UID */ private 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(Object 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}; } } ././@LongLink0000000000000000000000000000016100000000000011563 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/functors/NullIsExceptionPredicate.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/functors/NullIsExceptionPr0000644000175000017500000000613610777673476032525 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.functors; import java.io.Serializable; import org.apache.commons.collections.FunctorException; import org.apache.commons.collections.Predicate; /** * Predicate implementation that throws an exception if the input is null. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ public final class NullIsExceptionPredicate implements Predicate, PredicateDecorator, Serializable { /** Serial version UID */ private 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(Object 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}; } } ././@LongLink0000000000000000000000000000015500000000000011566 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/functors/NullIsFalsePredicate.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/functors/NullIsFalsePredic0000644000175000017500000000570710777673476032451 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.functors; import java.io.Serializable; import org.apache.commons.collections.Predicate; /** * Predicate implementation that returns false if the input is null. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ public final class NullIsFalsePredicate implements Predicate, PredicateDecorator, Serializable { /** Serial version UID */ private 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(Object 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}; } } ././@LongLink0000000000000000000000000000015400000000000011565 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/functors/NullIsTruePredicate.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/functors/NullIsTruePredica0000644000175000017500000000567210777673476032500 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.functors; import java.io.Serializable; import org.apache.commons.collections.Predicate; /** * Predicate implementation that returns true if the input is null. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ public final class NullIsTruePredicate implements Predicate, PredicateDecorator, Serializable { /** Serial version UID */ private 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(Object 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}; } } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/functors/NullPredicate.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/functors/NullPredicate.jav0000644000175000017500000000407410777673477032450 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.functors; import java.io.Serializable; import org.apache.commons.collections.Predicate; /** * Predicate implementation that returns true if the input is null. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ public final class NullPredicate implements Predicate, Serializable { /** Serial version UID */ private 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(Object object) { return (object == null); } } ././@LongLink0000000000000000000000000000014500000000000011565 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/functors/OnePredicate.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/functors/OnePredicate.java0000644000175000017500000001031010777673476032405 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.functors; import java.io.Serializable; import java.util.Collection; import org.apache.commons.collections.Predicate; /** * Predicate implementation that returns true if only one of the * predicates return true. * If the array of predicates is empty, then this predicate returns false. *

* NOTE: In versions prior to 3.2 an array size of zero or one * threw an exception. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne * @author Matt Benson */ public final class OnePredicate implements Predicate, PredicateDecorator, Serializable { /** Serial version UID */ private static final long serialVersionUID = -8125389089924745785L; /** The array of predicates to call */ private final Predicate[] iPredicates; /** * Factory to create the predicate. *

* If the array is size zero, the predicate always returns false. * If the array is size one, then that predicate is returned. * * @param predicates the predicates to check, cloned, not null * @return the any predicate * @throws IllegalArgumentException if the predicates array is null * @throws IllegalArgumentException if any predicate in the array is null */ public static Predicate getInstance(Predicate[] predicates) { FunctorUtils.validate(predicates); if (predicates.length == 0) { return FalsePredicate.INSTANCE; } if (predicates.length == 1) { return predicates[0]; } 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 */ 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(Object 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; } } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/functors/OrPredicate.java0000644000175000017500000000630710777673476032257 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.functors; import java.io.Serializable; import org.apache.commons.collections.Predicate; /** * Predicate implementation that returns true if either of the predicates return true. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ public final class OrPredicate implements Predicate, PredicateDecorator, Serializable { /** Serial version UID */ private 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(Object 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}; } } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/functors/package.html0000644000175000017500000000237010777673476031470 0ustar godgod

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.Transformer Transformer} and {@link org.apache.commons.collections.Factory Factory} interfaces. These provide simple callbacks for processing with collections.

././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/functors/PredicateDecorator.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/functors/PredicateDecorato0000644000175000017500000000310410777673476032507 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.functors; import org.apache.commons.collections.Predicate; /** * Defines a predicate that decorates one or more other predicates. *

* This interface enables tools to access the decorated predicates. * * @since Commons Collections 3.1 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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(); } ././@LongLink0000000000000000000000000000015500000000000011566 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/functors/PredicateTransformer.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/functors/PredicateTransfor0000644000175000017500000000550210777673476032551 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.functors; import java.io.Serializable; import org.apache.commons.collections.Predicate; import org.apache.commons.collections.Transformer; /** * Transformer implementation that calls a Predicate using the input object * and then returns the input. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ public class PredicateTransformer implements Transformer, Serializable { /** Serial version UID */ private 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 Object transform(Object 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; } } ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/functors/PrototypeFactory.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/functors/PrototypeFactory.0000644000175000017500000001664610777673476032560 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.functors; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import org.apache.commons.collections.Factory; import org.apache.commons.collections.FunctorException; /** * Factory implementation that creates a new instance each time based on a prototype. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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(Object prototype) { if (prototype == null) { return ConstantFactory.NULL_INSTANCE; } try { Method method = prototype.getClass().getMethod("clone", (Class[]) null); return new PrototypeCloneFactory(prototype, method); } catch (NoSuchMethodException ex) { try { prototype.getClass().getConstructor(new Class[] { prototype.getClass()}); return new InstantiateFactory( 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 */ private static final long serialVersionUID = 5604271422565175555L; /** The object to clone each time */ private final Object iPrototype; /** The method used to clone */ private transient Method iCloneMethod; /** * Constructor to store prototype. */ private PrototypeCloneFactory(Object 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", (Class[]) 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 Object create() { // needed for post-serialization if (iCloneMethod == null) { findCloneMethod(); } try { return iCloneMethod.invoke(iPrototype, (Object[])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 */ private 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 Object 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 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 } } } } } ././@LongLink0000000000000000000000000000015700000000000011570 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/functors/StringValueTransformer.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/functors/StringValueTransf0000644000175000017500000000424710777673476032560 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.functors; import java.io.Serializable; import org.apache.commons.collections.Transformer; /** * Transformer implementation that returns the result of calling * String.valueOf on the input object. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ public final class StringValueTransformer implements Transformer, Serializable { /** Serial version UID */ private static final long serialVersionUID = 7511110693171758606L; /** Singleton predicate instance */ public static final Transformer INSTANCE = new StringValueTransformer(); /** * Factory returning the singleton instance. * * @return the singleton instance * @since Commons Collections 3.1 */ public static Transformer getInstance() { return INSTANCE; } /** * 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 Object transform(Object input) { return String.valueOf(input); } } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/functors/SwitchClosure.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/functors/SwitchClosure.jav0000644000175000017500000001514510777673500032477 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.functors; import java.io.Serializable; import java.util.Iterator; import java.util.Map; import org.apache.commons.collections.Closure; import org.apache.commons.collections.Predicate; /** * Closure implementation calls the closure whose predicate returns true, * like a switch statement. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ public class SwitchClosure implements Closure, Serializable { /** Serial version UID */ private 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 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(Object 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; } } ././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/functors/SwitchTransformer.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/functors/SwitchTransformer0000644000175000017500000001613510777673477032623 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.functors; import java.io.Serializable; import java.util.Iterator; import java.util.Map; import org.apache.commons.collections.Predicate; import org.apache.commons.collections.Transformer; /** * Transformer implementation calls the transformer whose predicate returns true, * like a switch statement. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ public class SwitchTransformer implements Transformer, Serializable { /** Serial version UID */ private 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 return null * @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 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 = (Transformer) 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 it = predicatesAndTransformers.entrySet().iterator(); it.hasNext();) { Map.Entry entry = (Map.Entry) it.next(); preds[i] = (Predicate) entry.getKey(); transformers[i] = (Transformer) 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 return null */ 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 Object transform(Object input) { for (int i = 0; i < iPredicates.length; i++) { if (iPredicates[i].evaluate(input) == true) { return iTransformers[i].transform(input); } } return 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; } } ././@LongLink0000000000000000000000000000015500000000000011566 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/functors/TransformedPredicate.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/functors/TransformedPredic0000644000175000017500000000722210777673476032546 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.functors; import java.io.Serializable; import org.apache.commons.collections.Predicate; import org.apache.commons.collections.Transformer; /** * Predicate implementation that transforms the given object before invoking * another Predicate. * * @since Commons Collections 3.1 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * @author Alban Peignier * @author Stephen Colebourne */ public final class TransformedPredicate implements Predicate, PredicateDecorator, Serializable { /** Serial version UID */ private 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(Object object) { Object result = iTransformer.transform(object); return iPredicate.evaluate(result); } /** * 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}; } /** * Gets the transformer in use. * * @return the transformer */ public Transformer getTransformer() { return iTransformer; } } ././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/functors/TransformerClosure.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/functors/TransformerClosur0000644000175000017500000000535110777673476032626 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.functors; import java.io.Serializable; import org.apache.commons.collections.Closure; import org.apache.commons.collections.Transformer; /** * Closure implementation that calls a Transformer using the input object * and ignore the result. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ public class TransformerClosure implements Closure, Serializable { /** Serial version UID */ private 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(Object input) { iTransformer.transform(input); } /** * Gets the transformer. * * @return the transformer * @since Commons Collections 3.1 */ public Transformer getTransformer() { return iTransformer; } } ././@LongLink0000000000000000000000000000015500000000000011566 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/functors/TransformerPredicate.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/functors/TransformerPredic0000644000175000017500000000641010777673476032562 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.functors; import java.io.Serializable; import org.apache.commons.collections.FunctorException; import org.apache.commons.collections.Predicate; import org.apache.commons.collections.Transformer; /** * Predicate implementation that returns the result of a transformer. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ public final class TransformerPredicate implements Predicate, Serializable { /** Serial version UID */ private 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(Object object) { Object result = iTransformer.transform(object); if (result instanceof Boolean == false) { throw new FunctorException( "Transformer must return an instanceof Boolean, it was a " + (result == null ? "null object" : result.getClass().getName())); } return ((Boolean) result).booleanValue(); } /** * Gets the transformer. * * @return the transformer * @since Commons Collections 3.1 */ public Transformer getTransformer() { return iTransformer; } } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/functors/TruePredicate.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/functors/TruePredicate.jav0000644000175000017500000000401210777673476032444 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.functors; import java.io.Serializable; import org.apache.commons.collections.Predicate; /** * Predicate implementation that always returns true. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ public final class TruePredicate implements Predicate, Serializable { /** Serial version UID */ private 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(Object object) { return true; } } ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/functors/UniquePredicate.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/functors/UniquePredicate.j0000644000175000017500000000444510777673477032457 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.functors; import java.io.Serializable; import java.util.HashSet; import java.util.Set; import org.apache.commons.collections.Predicate; /** * Predicate implementation that returns true the first time an object is * passed into the predicate. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ public final class UniquePredicate implements Predicate, Serializable { /** Serial version UID */ private 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(Object object) { return iSet.add(object); } } ././@LongLink0000000000000000000000000000014500000000000011565 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/functors/WhileClosure.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/functors/WhileClosure.java0000644000175000017500000000777610777673476032476 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.functors; import java.io.Serializable; import org.apache.commons.collections.Closure; import org.apache.commons.collections.Predicate; /** * Closure implementation that executes a closure repeatedly until a condition is met, * like a do-while or while loop. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ public class WhileClosure implements Closure, Serializable { /** Serial version UID */ private 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(Object 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; } } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/iterators/0000755000175000017500000000000011010124151027310 5ustar godgod././@LongLink0000000000000000000000000000015700000000000011570 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/iterators/AbstractEmptyIterator.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/iterators/AbstractEmptyIte0000644000175000017500000000501510777673511032514 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.iterators; import java.util.NoSuchElementException; /** * Provides an implementation of an empty iterator. * * @since Commons Collections 3.1 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ abstract class AbstractEmptyIterator { /** * Constructor. */ protected AbstractEmptyIterator() { super(); } public boolean hasNext() { return false; } public Object next() { throw new NoSuchElementException("Iterator contains no elements"); } public boolean hasPrevious() { return false; } public Object previous() { throw new NoSuchElementException("Iterator contains no elements"); } public int nextIndex() { return 0; } public int previousIndex() { return -1; } public void add(Object obj) { throw new UnsupportedOperationException("add() not supported for empty Iterator"); } public void set(Object obj) { throw new IllegalStateException("Iterator contains no elements"); } public void remove() { throw new IllegalStateException("Iterator contains no elements"); } public Object getKey() { throw new IllegalStateException("Iterator contains no elements"); } public Object getValue() { throw new IllegalStateException("Iterator contains no elements"); } public Object setValue(Object value) { throw new IllegalStateException("Iterator contains no elements"); } public void reset() { // do nothing } } ././@LongLink0000000000000000000000000000016300000000000011565 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/iterators/AbstractIteratorDecorator.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/iterators/AbstractIterator0000644000175000017500000000457310777673511032555 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.iterators; import java.util.Iterator; /** * Provides basic behaviour for decorating an iterator with extra functionality. *

      * All methods are forwarded to the decorated iterator. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author James Strachan * @author Stephen Colebourne */ 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 Object next() { return iterator.next(); } public void remove() { iterator.remove(); } } ././@LongLink0000000000000000000000000000016700000000000011571 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/iterators/AbstractListIteratorDecorator.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/iterators/AbstractListIter0000644000175000017500000000560110777673511032514 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.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. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Rodney Waldhoff * @author Stephen Colebourne */ 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 Object next() { return iterator.next(); } public int nextIndex() { return iterator.nextIndex(); } public boolean hasPrevious() { return iterator.hasPrevious(); } public Object previous() { return iterator.previous(); } public int previousIndex() { return iterator.previousIndex(); } public void remove() { iterator.remove(); } public void set(Object obj) { iterator.set(obj); } public void add(Object obj) { iterator.add(obj); } } ././@LongLink0000000000000000000000000000016600000000000011570 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/iterators/AbstractMapIteratorDecorator.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/iterators/AbstractMapItera0000644000175000017500000000521510777673511032460 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.iterators; import org.apache.commons.collections.MapIterator; /** * Provides basic behaviour for decorating a map iterator with extra functionality. *

      * All methods are forwarded to the decorated map iterator. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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 Object next() { return iterator.next(); } public void remove() { iterator.remove(); } public Object getKey() { return iterator.getKey(); } public Object getValue() { return iterator.getValue(); } public Object setValue(Object obj) { return iterator.setValue(obj); } } ././@LongLink0000000000000000000000000000017500000000000011570 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/iterators/AbstractOrderedMapIteratorDecorator.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/iterators/AbstractOrderedM0000644000175000017500000000557010777673510032462 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.iterators; import org.apache.commons.collections.OrderedMapIterator; /** * Provides basic behaviour for decorating an ordered map iterator with extra functionality. *

      * All methods are forwarded to the decorated map iterator. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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 Object next() { return iterator.next(); } public boolean hasPrevious() { return iterator.hasPrevious(); } public Object previous() { return iterator.previous(); } public void remove() { iterator.remove(); } public Object getKey() { return iterator.getKey(); } public Object getValue() { return iterator.getValue(); } public Object setValue(Object obj) { return iterator.setValue(obj); } } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/iterators/ArrayIterator.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/iterators/ArrayIterator.ja0000644000175000017500000002020510777673510032446 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.iterators; import java.lang.reflect.Array; import java.util.NoSuchElementException; import org.apache.commons.collections.ResettableIterator; /** * 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.collections.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. * * @since Commons Collections 1.0 * @version $Revision: 647116 $ $Date: 2008-04-11 12:23:08 +0100 (Fri, 11 Apr 2008) $ * * @author James Strachan * @author Mauricio S. Moura * @author Michael A. Smith * @author Neil O'Toole * @author Stephen Colebourne */ 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 Object next() { if (hasNext() == false) { throw new NoSuchElementException(); } return 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; } } ././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/iterators/ArrayListIterator.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/iterators/ArrayListIterato0000644000175000017500000001726410777673510032542 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.iterators; import java.lang.reflect.Array; import java.util.ListIterator; import java.util.NoSuchElementException; import org.apache.commons.collections.ResettableListIterator; /** * 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. * * @see org.apache.commons.collections.iterators.ArrayIterator * @see java.util.Iterator * @see java.util.ListIterator * * @since Commons Collections 3.0 * @version $Revision: 647116 $ $Date: 2008-04-11 12:23:08 +0100 (Fri, 11 Apr 2008) $ * * @author Neil O'Toole * @author Stephen Colebourne * @author Phil Steitz */ 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 Object previous() { if (hasPrevious() == false) { throw new NoSuchElementException(); } this.lastItemIndex = --this.index; return 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 Object next() { if (hasNext() == false) { throw new NoSuchElementException(); } this.lastItemIndex = this.index; return 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(Object 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(Object 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; } } ././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/iterators/CollatingIterator.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/iterators/CollatingIterato0000644000175000017500000003126110777673511032536 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.iterators; import java.util.ArrayList; import java.util.BitSet; import java.util.Collection; import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import org.apache.commons.collections.list.UnmodifiableList; /** * 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(). * * @since Commons Collections 2.1 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Rodney Waldhoff * @author Stephen Colebourne */ 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 = (Iterator) 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 Object next() throws NoSuchElementException { if (hasNext() == false) { throw new NoSuchElementException(); } int leastIndex = least(); if (leastIndex == -1) { throw new NoSuchElementException(); } else { Object 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 = (Iterator) (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 = (Iterator)(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; Object 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 { Object 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 = (Iterator) iters.get(i); if (it.hasNext()) { return true; } } return false; } } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/iterators/EmptyIterator.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/iterators/EmptyIterator.ja0000644000175000017500000000370110777673510032470 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.iterators; import java.util.Iterator; import org.apache.commons.collections.ResettableIterator; /** * 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. * * @since Commons Collections 2.1.1 and 3.1 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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; /** * Constructor. */ protected EmptyIterator() { super(); } } ././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/iterators/EmptyListIterator.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/iterators/EmptyListIterato0000644000175000017500000000375310777673510032560 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.iterators; import java.util.ListIterator; import org.apache.commons.collections.ResettableListIterator; /** * 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. * * @since Commons Collections 2.1.1 and 3.1 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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 rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/iterators/EmptyMapIterator.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/iterators/EmptyMapIterator0000644000175000017500000000311610777673510032535 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.iterators; import org.apache.commons.collections.MapIterator; import org.apache.commons.collections.ResettableIterator; /** * Provides an implementation of an empty map iterator. * * @since Commons Collections 3.1 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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(); } } ././@LongLink0000000000000000000000000000015600000000000011567 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/iterators/EmptyOrderedIterator.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/iterators/EmptyOrderedIter0000644000175000017500000000315210777673511032517 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.iterators; import org.apache.commons.collections.OrderedIterator; import org.apache.commons.collections.ResettableIterator; /** * Provides an implementation of an empty ordered iterator. * * @since Commons Collections 3.1 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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(); } } ././@LongLink0000000000000000000000000000016100000000000011563 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/iterators/EmptyOrderedMapIterator.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/iterators/EmptyOrderedMapI0000644000175000017500000000320010777673510032433 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.iterators; import org.apache.commons.collections.OrderedMapIterator; import org.apache.commons.collections.ResettableIterator; /** * Provides an implementation of an empty ordered map iterator. * * @since Commons Collections 3.1 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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(); } } ././@LongLink0000000000000000000000000000015500000000000011566 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/iterators/EntrySetMapIterator.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/iterators/EntrySetMapItera0000644000175000017500000001335210777673511032473 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.iterators; import java.util.Iterator; import java.util.Map; import org.apache.commons.collections.MapIterator; import org.apache.commons.collections.ResettableIterator; /** * 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);
       * }
       * 
      * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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 Object next() { last = (Map.Entry) 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 Object 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 Object 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 Object setValue(Object 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[]"; } } } ././@LongLink0000000000000000000000000000015500000000000011566 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/iterators/EnumerationIterator.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/iterators/EnumerationItera0000644000175000017500000001153510777673510032546 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.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. * * @since Commons Collections 1.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author James Strachan * @author Daniel Rall */ 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 Object 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 Object 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. * * @exception IllegalStateException next() not called. * @exception 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; } } ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/iterators/FilterIterator.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/iterators/FilterIterator.j0000644000175000017500000001431010777673510032454 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.iterators; import java.util.Iterator; import java.util.NoSuchElementException; import org.apache.commons.collections.Predicate; /** * Decorates another {@link Iterator} using a predicate to filter elements. *

      * This iterator decorates the underlying iterator, only allowing through * those elements that match the specified {@link Predicate Predicate}. * * @since Commons Collections 1.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author James Strachan * @author Jan Sorensen * @author Ralph Wagner * @author Stephen Colebourne */ 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 Object 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 * @throws NullPointerException if either the iterator or predicate are null */ 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 NullPointerException if either the iterator or predicate are null * @throws NoSuchElementException if there are no more elements that * match the predicate */ public Object 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; nextObject = null; nextObjectSet = false; } //----------------------------------------------------------------------- /** * 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 predicate to use */ public void setPredicate(Predicate predicate) { this.predicate = predicate; nextObject = null; nextObjectSet = false; } //----------------------------------------------------------------------- /** * Set nextObject to the next object. If there are no more * objects then return false. Otherwise, return true. */ private boolean setNextObject() { while (iterator.hasNext()) { Object object = iterator.next(); if (predicate.evaluate(object)) { nextObject = object; nextObjectSet = true; return true; } } return false; } } ././@LongLink0000000000000000000000000000015400000000000011565 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/iterators/FilterListIterator.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/iterators/FilterListIterat0000644000175000017500000002026510777673510032525 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.iterators; import java.util.ListIterator; import java.util.NoSuchElementException; import org.apache.commons.collections.Predicate; /** * Decorates another {@link ListIterator} using a predicate to filter elements. *

      * This iterator decorates the underlying iterator, only allowing through * those elements that match the specified {@link Predicate Predicate}. * * @since Commons Collections 2.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Rodney Waldhoff */ 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 Object 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 Object 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 #setListIterator(ListIterator) setListIterator} * and {@link #setPredicate(Predicate) setPredicate} are 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 that will not function * until {@link #setListIterator(ListIterator) setListIterator} is invoked. * * @param predicate the predicate to use. */ public FilterListIterator(Predicate predicate) { super(); this.predicate = predicate; } //----------------------------------------------------------------------- /** Not supported. */ public void add(Object 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 Object next() { if(!nextObjectSet) { if(!setNextObject()) { throw new NoSuchElementException(); } } nextIndex++; Object temp = nextObject; clearNextObject(); return temp; } public int nextIndex() { return nextIndex; } public Object previous() { if(!previousObjectSet) { if(!setPreviousObject()) { throw new NoSuchElementException(); } } nextIndex--; Object 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(Object 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()) { Object 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()) { Object object = iterator.previous(); if(predicate.evaluate(object)) { previousObject = object; previousObjectSet = true; return true; } } return false; } } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/iterators/IteratorChain.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/iterators/IteratorChain.ja0000644000175000017500000002365510777673511032427 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.iterators; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import org.apache.commons.collections.list.UnmodifiableList; /** * 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. * * @since Commons Collections 2.1 * @version $Revision: 647116 $ $Date: 2008-04-11 12:23:08 +0100 (Fri, 11 Apr 2008) $ * * @author Morgan Delagrange * @author Stephen Colebourne */ 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 it = iterators.iterator(); it.hasNext();) { Iterator item = (Iterator) it.next(); addIterator(item); } } //----------------------------------------------------------------------- /** * 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 = (Iterator) 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 = (Iterator) 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 Object 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(); if (currentIterator == null) { updateCurrentIterator(); } lastUsedIterator.remove(); } } ././@LongLink0000000000000000000000000000015500000000000011566 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/iterators/IteratorEnumeration.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/iterators/IteratorEnumerat0000644000175000017500000000612310777673510032562 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.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. * * @since Commons Collections 1.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author James Strachan */ 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 Object 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; } } ././@LongLink0000000000000000000000000000015500000000000011566 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/iterators/ListIteratorWrapper.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/iterators/ListIteratorWrap0000644000175000017500000001453010777673511032551 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.iterators; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import org.apache.commons.collections.ResettableListIterator; /** * Converts an iterator into a list iterator by caching the returned entries. *

      * The ListIterator interface has additional useful methods * for navigation - previous() and the index methods. * This class allows a regular Iterator to behave as a * ListIterator. It achieves this by building a list internally * of as the underlying iterator is traversed. *

      * The optional operations of ListIterator are not supported. *

      * This class implements ResettableListIterator from Commons Collections 3.2. * * @since Commons Collections 2.1 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Morgan Delagrange * @author Stephen Colebourne */ public class ListIteratorWrapper implements ResettableListIterator { /** Message used when remove, set or add are called. */ private static final String UNSUPPORTED_OPERATION_MESSAGE = "ListIteratorWrapper does not support optional operations of ListIterator."; /** The underlying iterator being decorated. */ private final Iterator iterator; /** The list being used to cache the iterator. */ private final List list = new ArrayList(); /** The current index of this iterator. */ private int currentIndex = 0; /** The current index of the wrapped iterator. */ private int wrappedIteratorIndex = 0; // 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 obj the object to add, ignored * @throws UnsupportedOperationException always */ public void add(Object obj) 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 Object next() throws NoSuchElementException { if (currentIndex < wrappedIteratorIndex) { ++currentIndex; return list.get(currentIndex - 1); } Object 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 Object 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 obj the object to set, ignored * @throws UnsupportedOperationException always */ public void set(Object obj) throws UnsupportedOperationException { throw new UnsupportedOperationException(UNSUPPORTED_OPERATION_MESSAGE); } // ResettableIterator interface //------------------------------------------------------------------------- /** * Resets this iterator back to the position at which the iterator * was created. * * @since Commons Collections 3.2 */ public void reset() { currentIndex = 0; } } ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/iterators/LoopingIterator.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/iterators/LoopingIterator.0000644000175000017500000001057310777673510032473 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.iterators; import java.util.Collection; import java.util.Iterator; import java.util.NoSuchElementException; import org.apache.commons.collections.ResettableIterator; /** * 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. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Jonathan Carlson * @author Stephen Colebourne */ 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 Object 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(); } } ././@LongLink0000000000000000000000000000015500000000000011566 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/iterators/LoopingListIterator.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/iterators/LoopingListItera0000644000175000017500000002134010777673510032516 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.iterators; import java.util.List; import java.util.ListIterator; import java.util.NoSuchElementException; import org.apache.commons.collections.ResettableListIterator; /** * A ListIterator that restarts when it reaches the end or when it * reaches the beginning. *

      * The iterator will loop continuously around the provided list, * unless there are no elements in the collection to begin with, or * all of the elements have been {@link #remove removed}. *

      * Concurrent modifications are not directly supported, and for most * collection implementations will throw a * ConcurrentModificationException. * * @since Commons Collections 3.2 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Eric Crampton */ public class LoopingListIterator implements ResettableListIterator { /** The list to base the iterator on */ private List list; /** The current list iterator */ private ListIterator iterator; /** * Constructor that wraps a list. *

      * There is no way to reset a ListIterator instance without * recreating it from the original source, so the List must be * passed in and a reference to it held. * * @param list the list to wrap * @throws NullPointerException if the list it null */ public LoopingListIterator(List list) { if (list == null) { throw new NullPointerException("The list must not be null"); } this.list = list; reset(); } /** * Returns whether this iterator has any more elements. *

      * Returns false only if the list originally had zero elements, or * all elements have been {@link #remove removed}. * * @return true if there are more elements */ public boolean hasNext() { return !list.isEmpty(); } /** * Returns the next object in the list. *

      * If at the end of the list, returns the first element. * * @return the object after the last element returned * @throws NoSuchElementException if there are no elements in the list */ public Object next() { if (list.isEmpty()) { throw new NoSuchElementException( "There are no elements for this iterator to loop on"); } if (iterator.hasNext() == false) { reset(); } return iterator.next(); } /** * Returns the index of the element that would be returned by a * subsequent call to {@link #next}. *

      * As would be expected, if the iterator is at the physical end of * the underlying list, 0 is returned, signifying the beginning of * the list. * * @return the index of the element that would be returned if next() were called * @throws NoSuchElementException if there are no elements in the list */ public int nextIndex() { if (list.isEmpty()) { throw new NoSuchElementException( "There are no elements for this iterator to loop on"); } if (iterator.hasNext() == false) { return 0; } else { return iterator.nextIndex(); } } /** * Returns whether this iterator has any more previous elements. *

      * Returns false only if the list originally had zero elements, or * all elements have been {@link #remove removed}. * * @return true if there are more elements */ public boolean hasPrevious() { return !list.isEmpty(); } /** * Returns the previous object in the list. *

      * If at the beginning of the list, return the last element. Note * that in this case, traversal to find that element takes linear time. * * @return the object before the last element returned * @throws NoSuchElementException if there are no elements in the list */ public Object previous() { if (list.isEmpty()) { throw new NoSuchElementException( "There are no elements for this iterator to loop on"); } if (iterator.hasPrevious() == false) { Object result = null; while (iterator.hasNext()) { result = iterator.next(); } iterator.previous(); return result; } else { return iterator.previous(); } } /** * Returns the index of the element that would be returned by a * subsequent call to {@link #previous}. *

      * As would be expected, if at the iterator is at the physical * beginning of the underlying list, the list's size minus one is * returned, signifying the end of the list. * * @return the index of the element that would be returned if previous() were called * @throws NoSuchElementException if there are no elements in the list */ public int previousIndex() { if (list.isEmpty()) { throw new NoSuchElementException( "There are no elements for this iterator to loop on"); } if (iterator.hasPrevious() == false) { return list.size() - 1; } else { return iterator.previousIndex(); } } /** * Removes the previously retrieved item from the underlying list. *

      * This feature is only supported if the underlying list's * {@link List#iterator iterator} method returns an implementation * that supports it. *

      * This method can only be called after at least one {@link #next} * or {@link #previous} method call. After a removal, the remove * method may not be called again until another {@link #next} or * {@link #previous} has been performed. If the {@link #reset} is * called, then remove may not be called until {@link #next} or * {@link #previous} is called again. * * @throws UnsupportedOperationException if the remove method is * not supported by the iterator implementation of the underlying * list */ public void remove() { iterator.remove(); } /** * Inserts the specified element into the underlying list. *

      * The element is inserted before the next element that would be * returned by {@link #next}, if any, and after the next element * that would be returned by {@link #previous}, if any. *

      * This feature is only supported if the underlying list's * {@link List#listIterator} method returns an implementation * that supports it. * * @param obj the element to insert * @throws UnsupportedOperationException if the add method is not * supported by the iterator implementation of the underlying list */ public void add(Object obj) { iterator.add(obj); } /** * Replaces the last element that was returned by {@link #next} or * {@link #previous}. *

      * This feature is only supported if the underlying list's * {@link List#listIterator} method returns an implementation * that supports it. * * @param obj the element with which to replace the last element returned * @throws UnsupportedOperationException if the set method is not * supported by the iterator implementation of the underlying list */ public void set(Object obj) { iterator.set(obj); } /** * Resets the iterator back to the start of the list. */ public void reset() { iterator = list.listIterator(); } /** * Gets the size of the list underlying the iterator. * * @return the current list size */ public int size() { return list.size(); } } ././@LongLink0000000000000000000000000000015500000000000011566 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/iterators/ObjectArrayIterator.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/iterators/ObjectArrayItera0000644000175000017500000001633410777673511032470 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.iterators; import java.util.Iterator; import java.util.NoSuchElementException; import org.apache.commons.collections.ResettableIterator; /** * 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. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author James Strachan * @author Mauricio S. Moura * @author Michael A. Smith * @author Neil O'Toole * @author Stephen Colebourne * @author Phil Steitz */ public class ObjectArrayIterator implements Iterator, ResettableIterator { /** The array */ protected Object[] 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(Object[] 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(Object 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(Object 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 Object 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 Object[] 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(Object[] 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; } } ././@LongLink0000000000000000000000000000016100000000000011563 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/iterators/ObjectArrayListIterator.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/iterators/ObjectArrayListI0000644000175000017500000001647210777673510032452 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.iterators; import java.util.ListIterator; import java.util.NoSuchElementException; import org.apache.commons.collections.ResettableListIterator; /** * 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. * * @see org.apache.commons.collections.iterators.ObjectArrayIterator * @see java.util.Iterator * @see java.util.ListIterator * * @since Commons Collections 3.0 * @version $Revision: 647116 $ $Date: 2008-04-11 12:23:08 +0100 (Fri, 11 Apr 2008) $ * * @author Neil O'Toole * @author Stephen Colebourne * @author Phil Steitz */ 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(Object[] 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(Object[] 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(Object[] 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 Object 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 Object 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(Object 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(Object 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; } } ././@LongLink0000000000000000000000000000015500000000000011566 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/iterators/ObjectGraphIterator.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/iterators/ObjectGraphItera0000644000175000017500000002203110777673510032441 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.iterators; import java.util.Iterator; import java.util.NoSuchElementException; import org.apache.commons.collections.ArrayStack; import org.apache.commons.collections.Transformer; /** * 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. * * @since Commons Collections 3.1 * @version $Revision: 647116 $ $Date: 2008-04-11 12:23:08 +0100 (Fri, 11 Apr 2008) $ * * @author Stephen Colebourne */ 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; } } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/iterators/package.html0000644000175000017500000000226510777673511031632 0ustar godgod

      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. ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/iterators/ProxyIterator.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/iterators/ProxyIterator.ja0000644000175000017500000000642010777673511032515 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.iterators; import java.util.Iterator; /** * A Proxy {@link Iterator Iterator} which delegates its methods to a proxy instance. * * @deprecated Use AbstractIteratorDecorator. Will be removed in v4.0 * @since Commons Collections 1.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author James Strachan */ public class ProxyIterator implements Iterator { /** Holds value of property iterator. */ private Iterator iterator; // Constructors //------------------------------------------------------------------------- /** * Constructs a new ProxyIterator that will not function * until {@link #setIterator(Iterator)} is called. */ public ProxyIterator() { super(); } /** * Constructs a new ProxyIterator that will use the * given iterator. * * @param iterator the underlying iterator */ public ProxyIterator(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 hasNext() { return getIterator().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 * raises it because it has no more elements */ public Object next() { return getIterator().next(); } /** * Removes the last returned element from the collection that spawned * the underlying iterator. */ public void remove() { getIterator().remove(); } // Properties //------------------------------------------------------------------------- /** Getter for property iterator. * @return Value of property iterator. */ public Iterator getIterator() { return iterator; } /** Setter for property iterator. * @param iterator New value of property iterator. */ public void setIterator(Iterator iterator) { this.iterator = iterator; } } ././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/iterators/ProxyListIterator.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/iterators/ProxyListIterato0000644000175000017500000001156010777673511032577 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.iterators; import java.util.ListIterator; /** * A proxy {@link ListIterator ListIterator} which delegates its * methods to a proxy instance. * * @deprecated Use AbstractListIteratorDecorator. Will be removed in v4.0 * @since Commons Collections 2.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Rodney Waldhoff */ public class ProxyListIterator implements ListIterator { /** Holds value of property "iterator". */ private ListIterator iterator; // Constructors //------------------------------------------------------------------------- /** * Constructs a new ProxyListIterator that will not * function until {@link #setListIterator(ListIterator) setListIterator} * is invoked. */ public ProxyListIterator() { super(); } /** * Constructs a new ProxyListIterator that will use the * given list iterator. * * @param iterator the list iterator to use */ public ProxyListIterator(ListIterator iterator) { super(); this.iterator = iterator; } // ListIterator interface //------------------------------------------------------------------------- /** * Invokes the underlying {@link ListIterator#add(Object)} method. * * @throws NullPointerException if the underlying iterator is null */ public void add(Object o) { getListIterator().add(o); } /** * Invokes the underlying {@link ListIterator#hasNext()} method. * * @throws NullPointerException if the underlying iterator is null */ public boolean hasNext() { return getListIterator().hasNext(); } /** * Invokes the underlying {@link ListIterator#hasPrevious()} method. * * @throws NullPointerException if the underlying iterator is null */ public boolean hasPrevious() { return getListIterator().hasPrevious(); } /** * Invokes the underlying {@link ListIterator#next()} method. * * @throws NullPointerException if the underlying iterator is null */ public Object next() { return getListIterator().next(); } /** * Invokes the underlying {@link ListIterator#nextIndex()} method. * * @throws NullPointerException if the underlying iterator is null */ public int nextIndex() { return getListIterator().nextIndex(); } /** * Invokes the underlying {@link ListIterator#previous()} method. * * @throws NullPointerException if the underlying iterator is null */ public Object previous() { return getListIterator().previous(); } /** * Invokes the underlying {@link ListIterator#previousIndex()} method. * * @throws NullPointerException if the underlying iterator is null */ public int previousIndex() { return getListIterator().previousIndex(); } /** * Invokes the underlying {@link ListIterator#remove()} method. * * @throws NullPointerException if the underlying iterator is null */ public void remove() { getListIterator().remove(); } /** * Invokes the underlying {@link ListIterator#set(Object)} method. * * @throws NullPointerException if the underlying iterator is null */ public void set(Object o) { getListIterator().set(o); } // Properties //------------------------------------------------------------------------- /** * Getter for property iterator. * @return Value of property iterator. */ public ListIterator getListIterator() { return iterator; } /** * Setter for property iterator. * @param iterator New value of property iterator. */ public void setListIterator(ListIterator iterator) { this.iterator = iterator; } } ././@LongLink0000000000000000000000000000015500000000000011566 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/iterators/ReverseListIterator.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/iterators/ReverseListItera0000644000175000017500000001336310777673510032530 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.iterators; import java.util.List; import java.util.ListIterator; import org.apache.commons.collections.ResettableListIterator; /** * Iterates backwards through a List, starting with the last element * and continuing to the first. This is useful for looping around * a list in reverse order without needing to actually reverse the list. *

      * The first call to next() will return the last element * from the list, and so on. The hasNext() method works * in concert with the next() method as expected. * However, the nextIndex() method returns the correct * index in the list, thus it starts high and reduces as the iteration * continues. The previous methods work similarly. * * @author Serge Knystautas * @author Stephen Colebourne * @since Commons Collections 3.2 * @version $Revision: $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ */ public class ReverseListIterator implements ResettableListIterator { /** The list being wrapped. */ private final List list; /** The list iterator being wrapped. */ private ListIterator iterator; /** Flag to indicate if updating is possible at the moment. */ private boolean validForUpdate = true; /** * Constructor that wraps a list. * * @param list the list to create a reversed iterator for * @throws NullPointerException if the list is null */ public ReverseListIterator(List list) { super(); this.list = list; iterator = list.listIterator(list.size()); } //----------------------------------------------------------------------- /** * Checks whether there is another element. * * @return true if there is another element */ public boolean hasNext() { return iterator.hasPrevious(); } /** * Gets the next element. * The next element is the previous in the list. * * @return the next element in the iterator */ public Object next() { Object obj = iterator.previous(); validForUpdate = true; return obj; } /** * Gets the index of the next element. * * @return the index of the next element in the iterator */ public int nextIndex() { return iterator.previousIndex(); } /** * Checks whether there is a previous element. * * @return true if there is a previous element */ public boolean hasPrevious() { return iterator.hasNext(); } /** * Gets the previous element. * The next element is the previous in the list. * * @return the previous element in the iterator */ public Object previous() { Object obj = iterator.next(); validForUpdate = true; return obj; } /** * Gets the index of the previous element. * * @return the index of the previous element in the iterator */ public int previousIndex() { return iterator.nextIndex(); } /** * Removes the last returned element. * * @throws UnsupportedOperationException if the list is unmodifiable * @throws IllegalStateException if there is no element to remove */ public void remove() { if (validForUpdate == false) { throw new IllegalStateException("Cannot remove from list until next() or previous() called"); } iterator.remove(); } /** * Replaces the last returned element. * * @param obj the object to set * @throws UnsupportedOperationException if the list is unmodifiable * @throws IllegalStateException if the iterator is not in a valid state for set */ public void set(Object obj) { if (validForUpdate == false) { throw new IllegalStateException("Cannot set to list until next() or previous() called"); } iterator.set(obj); } /** * Adds a new element to the list between the next and previous elements. * * @param obj the object to add * @throws UnsupportedOperationException if the list is unmodifiable * @throws IllegalStateException if the iterator is not in a valid state for set */ public void add(Object obj) { // the validForUpdate flag is needed as the necessary previous() // method call re-enables remove and add if (validForUpdate == false) { throw new IllegalStateException("Cannot add to list until next() or previous() called"); } validForUpdate = false; iterator.add(obj); iterator.previous(); } /** * Resets the iterator back to the start (which is the * end of the list as this is a reversed iterator) */ public void reset() { iterator = list.listIterator(list.size()); } } ././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/iterators/SingletonIterator.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/iterators/SingletonIterato0000644000175000017500000001025010777673511032557 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.iterators; import java.util.Iterator; import java.util.NoSuchElementException; import org.apache.commons.collections.ResettableIterator; /** * SingletonIterator is an {@link Iterator} over a single * object instance. * * @since Commons Collections 2.0 * @version $Revision: 647116 $ $Date: 2008-04-11 12:23:08 +0100 (Fri, 11 Apr 2008) $ * * @author James Strachan * @author Stephen Colebourne * @author Rodney Waldhoff */ 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 Object object; /** * Constructs a new SingletonIterator where remove * is a permitted operation. * * @param object the single object to return from the iterator */ public SingletonIterator(Object 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(Object 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 Object 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; } } ././@LongLink0000000000000000000000000000015700000000000011570 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/iterators/SingletonListIterator.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/iterators/SingletonListIte0000644000175000017500000001254210777673510032532 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.iterators; import java.util.ListIterator; import java.util.NoSuchElementException; import org.apache.commons.collections.ResettableListIterator; /** * SingletonIterator is an {@link ListIterator} over a single * object instance. * * @since Commons Collections 2.1 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne * @author Rodney Waldhoff */ public class SingletonListIterator implements ListIterator, ResettableListIterator { private boolean beforeFirst = true; private boolean nextCalled = false; private boolean removed = false; private Object object; /** * Constructs a new SingletonListIterator. * * @param object the single object to return from the iterator */ public SingletonListIterator(Object 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 Object 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 Object 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(Object 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(Object obj) { if (!nextCalled || removed) { throw new IllegalStateException(); } this.object = obj; } /** * Reset the iterator back to the start. */ public void reset() { beforeFirst = true; nextCalled = false; } } ././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/iterators/TransformIterator.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/iterators/TransformIterato0000644000175000017500000001136510777673510032577 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.iterators; import java.util.Iterator; import org.apache.commons.collections.Transformer; /** * Decorates an iterator such that each element returned is transformed. * * @since Commons Collections 1.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author James Strachan * @author Stephen Colebourne */ 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 Object 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 Object transform(Object source) { if (transformer != null) { return transformer.transform(source); } return source; } } ././@LongLink0000000000000000000000000000015600000000000011567 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/iterators/UniqueFilterIterator.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/iterators/UniqueFilterIter0000644000175000017500000000332410777673510032530 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.iterators; import java.util.Iterator; import org.apache.commons.collections.functors.UniquePredicate; /** * A FilterIterator which only returns "unique" Objects. Internally, * the Iterator maintains a Set of objects it has already encountered, * and duplicate Objects are skipped. * * @since Commons Collections 2.1 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Morgan Delagrange */ public class UniqueFilterIterator extends FilterIterator { //------------------------------------------------------------------------- /** * Constructs a new UniqueFilterIterator. * * @param iterator the iterator to use */ public UniqueFilterIterator( Iterator iterator ) { super(iterator, UniquePredicate.getInstance()); } } ././@LongLink0000000000000000000000000000015600000000000011567 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/iterators/UnmodifiableIterator.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/iterators/UnmodifiableIter0000644000175000017500000000522210777673510032511 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.iterators; import java.util.Iterator; import org.apache.commons.collections.Unmodifiable; /** * Decorates an iterator such that it cannot be modified. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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 Object next() { return iterator.next(); } public void remove() { throw new UnsupportedOperationException("remove() is not supported"); } } ././@LongLink0000000000000000000000000000016200000000000011564 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/iterators/UnmodifiableListIterator.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/iterators/UnmodifiableList0000644000175000017500000000623610777673510032527 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.iterators; import java.util.ListIterator; import org.apache.commons.collections.Unmodifiable; /** * Decorates a list iterator such that it cannot be modified. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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 Object next() { return iterator.next(); } public int nextIndex() { return iterator.nextIndex(); } public boolean hasPrevious() { return iterator.hasPrevious(); } public Object previous() { return iterator.previous(); } public int previousIndex() { return iterator.previousIndex(); } public void remove() { throw new UnsupportedOperationException("remove() is not supported"); } public void set(Object obj) { throw new UnsupportedOperationException("set() is not supported"); } public void add(Object obj) { throw new UnsupportedOperationException("add() is not supported"); } } ././@LongLink0000000000000000000000000000016100000000000011563 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/iterators/UnmodifiableMapIterator.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/iterators/UnmodifiableMapI0000644000175000017500000000561710777673510032444 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.iterators; import org.apache.commons.collections.MapIterator; import org.apache.commons.collections.Unmodifiable; /** * Decorates a map iterator such that it cannot be modified. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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 Object next() { return iterator.next(); } public Object getKey() { return iterator.getKey(); } public Object getValue() { return iterator.getValue(); } public Object setValue(Object value) { throw new UnsupportedOperationException("setValue() is not supported"); } public void remove() { throw new UnsupportedOperationException("remove() is not supported"); } } ././@LongLink0000000000000000000000000000017000000000000011563 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/iterators/UnmodifiableOrderedMapIterator.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/iterators/UnmodifiableOrde0000644000175000017500000000620110777673510032475 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.iterators; import org.apache.commons.collections.OrderedMapIterator; import org.apache.commons.collections.Unmodifiable; /** * Decorates an ordered map iterator such that it cannot be modified. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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 Object next() { return iterator.next(); } public boolean hasPrevious() { return iterator.hasPrevious(); } public Object previous() { return iterator.previous(); } public Object getKey() { return iterator.getKey(); } public Object getValue() { return iterator.getValue(); } public Object setValue(Object value) { throw new UnsupportedOperationException("setValue() is not supported"); } public void remove() { throw new UnsupportedOperationException("remove() is not supported"); } } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/keyvalue/0000755000175000017500000000000011010124151027121 5ustar godgod././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/keyvalue/AbstractKeyValue.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/keyvalue/AbstractKeyValue.0000644000175000017500000000462210777673516032400 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.keyvalue; import org.apache.commons.collections.KeyValue; /** * Abstract pair class to assist with creating KeyValue * and {@link java.util.Map.Entry Map.Entry} implementations. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author James Strachan * @author Michael A. Smith * @author Neil O'Toole * @author Stephen Colebourne */ public abstract class AbstractKeyValue implements KeyValue { /** The key */ protected Object key; /** The value */ protected Object 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(Object key, Object value) { super(); this.key = key; this.value = value; } /** * Gets the key from the pair. * * @return the key */ public Object getKey() { return key; } /** * Gets the value from the pair. * * @return the value */ public Object 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(); } } ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/keyvalue/AbstractMapEntry.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/keyvalue/AbstractMapEntry.0000644000175000017500000000642010777673516032410 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.keyvalue; import java.util.Map; /** * Abstract Pair class to assist with creating correct * {@link java.util.Map.Entry Map.Entry} implementations. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author James Strachan * @author Michael A. Smith * @author Neil O'Toole * @author Stephen Colebourne */ 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(Object key, Object 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 Object setValue(Object value) { Object 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()); } } ././@LongLink0000000000000000000000000000016200000000000011564 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/keyvalue/AbstractMapEntryDecorator.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/keyvalue/AbstractMapEntryD0000644000175000017500000000515710777673516032444 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.keyvalue; import java.util.Map; import org.apache.commons.collections.KeyValue; /** * Provides a base decorator that allows additional functionality to be * added to a {@link java.util.Map.Entry Map.Entry}. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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 Object getKey() { return entry.getKey(); } public Object getValue() { return entry.getValue(); } public Object setValue(Object 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(); } } ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/keyvalue/DefaultKeyValue.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/keyvalue/DefaultKeyValue.j0000644000175000017500000001226410777673516032374 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.keyvalue; import java.util.Map; import org.apache.commons.collections.KeyValue; /** * A mutable KeyValue pair that does not implement * {@link java.util.Map.Entry Map.Entry}. *

      * Note that a DefaultKeyValue instance may not contain * itself as a key or value. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author James Strachan * @author Michael A. Smith * @author Neil O'Toole * @author Stephen Colebourne */ 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 Object key, final Object 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 Map.Entry. * * @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 Object setKey(final Object key) { if (key == this) { throw new IllegalArgumentException("DefaultKeyValue may not contain itself as a key."); } final Object old = this.key; this.key = key; return old; } /** * Sets the value. * * @return the old value of the value * @param value the new value * @throws IllegalArgumentException if value is this object */ public Object setValue(final Object value) { if (value == this) { throw new IllegalArgumentException("DefaultKeyValue may not contain itself as a value."); } final Object 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()); } } ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/keyvalue/DefaultMapEntry.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/keyvalue/DefaultMapEntry.j0000644000175000017500000000451410777673516032405 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.keyvalue; import java.util.Map; import org.apache.commons.collections.KeyValue; /** * A restricted implementation of {@link java.util.Map.Entry} that prevents * the Map.Entry contract from being broken. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author James Strachan * @author Michael A. Smith * @author Neil O'Toole * @author Stephen Colebourne */ 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 Object key, final Object 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 Map.Entry. * * @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()); } } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/keyvalue/MultiKey.java0000644000175000017500000002073110777673516031573 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.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);
       * 
      * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Howard Lewis Ship * @author Stephen Colebourne */ 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 Object[] 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 key1 the first key * @param key2 the second key */ public MultiKey(Object key1, Object key2) { this(new Object[] {key1, key2}, false); } /** * Constructor taking three keys. *

      * The keys should be immutable * If they are not then they must not be changed after adding to the MultiKey. * * @param key1 the first key * @param key2 the second key * @param key3 the third key */ public MultiKey(Object key1, Object key2, Object key3) { this(new Object[] {key1, key2, key3}, false); } /** * Constructor taking four keys. *

      * The keys should be immutable * If they are not then they must not be changed after adding to the MultiKey. * * @param key1 the first key * @param key2 the second key * @param key3 the third key * @param key4 the fourth key */ public MultiKey(Object key1, Object key2, Object key3, Object key4) { this(new Object[] {key1, key2, key3, key4}, false); } /** * Constructor taking five keys. *

      * The keys should be immutable * If they are not then they must not be changed after adding to the MultiKey. * * @param key1 the first key * @param key2 the second key * @param key3 the third key * @param key4 the fourth key * @param key5 the fifth key */ public MultiKey(Object key1, Object key2, Object key3, Object key4, Object key5) { this(new Object[] {key1, key2, key3, key4, key5}, false); } /** * Constructor taking an array of keys which is cloned. *

      * The keys should be immutable * If they are not then they must not be changed after adding to the MultiKey. *

      * This is equivalent to new MultiKey(keys, true). * * @param keys the array of keys, not null * @throws IllegalArgumentException if the key array is null */ public MultiKey(Object[] 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(Object[] keys, boolean makeClone) { super(); if (keys == null) { throw new IllegalArgumentException("The array of keys must not be null"); } if (makeClone) { this.keys = (Object[]) 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 Object[] getKeys() { return (Object[]) 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 Object 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(); } } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/keyvalue/package.html0000644000175000017500000000246010777673516031445 0ustar godgod

      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
././@LongLink0000000000000000000000000000014500000000000011565 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/keyvalue/TiedMapEntry.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/keyvalue/TiedMapEntry.java0000644000175000017500000001021510777673516032371 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.keyvalue; import java.io.Serializable; import java.util.Map; import org.apache.commons.collections.KeyValue; /** * A {@link java.util.Map.Entry 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. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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 Object key; /** * Constructs a new entry with the given Map and key. * * @param map the map * @param key the key */ public TiedMapEntry(Map map, Object key) { super(); this.map = map; this.key = key; } // Map.Entry interface //------------------------------------------------------------------------- /** * Gets the key of this entry * * @return the key */ public Object getKey() { return key; } /** * Gets the value of this entry direct from the map. * * @return the value */ public Object 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 Object setValue(Object value) { if (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(); } } ././@LongLink0000000000000000000000000000015500000000000011566 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/keyvalue/UnmodifiableMapEntry.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/keyvalue/UnmodifiableMapEn0000644000175000017500000000523710777673516032433 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.keyvalue; import java.util.Map; import org.apache.commons.collections.KeyValue; import org.apache.commons.collections.Unmodifiable; /** * A {@link java.util.Map.Entry Map.Entry} that throws * UnsupportedOperationException when setValue is called. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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 Object key, final Object 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 Map.Entry. * * @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 Object setValue(Object value) { throw new UnsupportedOperationException("setValue() is not supported"); } } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/list/0000755000175000017500000000000011010124151026247 5ustar godgod././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/list/AbstractLinkedList.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/list/AbstractLinkedList.ja0000644000175000017500000007720410777673507032364 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.list; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.lang.reflect.Array; import java.util.AbstractList; import java.util.Collection; import java.util.ConcurrentModificationException; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.NoSuchElementException; import org.apache.commons.collections.OrderedIterator; /** * 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. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Rich Dougherty * @author Phil Steitz * @author Stephen Colebourne */ 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 Object 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(), 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(), 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 Object[] toArray(Object[] array) { // Extend the array if needed if (array.length < size) { Class componentType = array.getClass().getComponentType(); array = (Object[]) Array.newInstance(componentType, size); } // Copy the values into the array int i = 0; for (Node node = header.next; node != header; node = node.next, i++) { array[i] = 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(Object value) { addLast(value); return true; } public void add(int index, Object 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, value); } return true; } //----------------------------------------------------------------------- public Object remove(int index) { Node node = getNode(index, false); Object 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(), 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 Object set(int index, Object value) { Node node = getNode(index, false); Object oldValue = node.getValue(); updateNode(node, value); return oldValue; } public void clear() { removeAllNodes(); } //----------------------------------------------------------------------- public Object getFirst() { Node node = header.next; if (node == header) { throw new NoSuchElementException(); } return node.getValue(); } public Object getLast() { Node node = header.previous; if (node == header) { throw new NoSuchElementException(); } return node.getValue(); } public boolean addFirst(Object o) { addNodeAfter(header, o); return true; } public boolean addLast(Object o) { addNodeBefore(header, o); return true; } public Object removeFirst() { Node node = header.next; if (node == header) { throw new NoSuchElementException(); } Object oldValue = node.getValue(); removeNode(node); return oldValue; } public Object removeLast() { Node node = header.previous; if (node == header) { throw new NoSuchElementException(); } Object 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(Object value1, Object 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, Object 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(Object 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, Object 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, Object 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(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 Object 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(Object 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, Object 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 Object getValue() { return value; } /** * Sets the value of the node. * * @param value the value * @since Commons Collections 3.1 */ protected void setValue(Object 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 Object next() { checkModCount(); if (!hasNext()) { throw new NoSuchElementException("No element at index " + nextIndex + "."); } Object value = next.getValue(); current = next; next = next.next; nextIndex++; return value; } public boolean hasPrevious() { return next.previous != parent.header; } public Object previous() { checkModCount(); if (!hasPrevious()) { throw new NoSuchElementException("Already at start of list."); } next = next.previous; Object 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(); if (current == next) { // remove() following previous() next = next.next; parent.removeNode(getLastNodeReturned()); } else { // remove() following next() parent.removeNode(getLastNodeReturned()); nextIndex--; } current = null; expectedModCount++; } public void set(Object obj) { checkModCount(); getLastNodeReturned().setValue(obj); } public void add(Object 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(Object 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 */ AbstractLinkedList parent; /** Offset from the main list */ int offset; /** Sublist size */ int size; /** Sublist modCount */ 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 Object get(int index) { rangeCheck(index, size); checkModCount(); return parent.get(index + offset); } public void add(int index, Object obj) { rangeCheck(index, size + 1); checkModCount(); parent.add(index + offset, obj); expectedModCount = parent.modCount; size++; LinkedSubList.this.modCount++; } public Object remove(int index) { rangeCheck(index, size); checkModCount(); Object 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 Object set(int index, Object 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(); } } } } ././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/list/AbstractListDecorator.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/list/AbstractListDecorator0000644000175000017500000000616710777673507032507 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.list; import java.util.Collection; import java.util.List; import java.util.ListIterator; import org.apache.commons.collections.collection.AbstractCollectionDecorator; /** * Decorates another List to provide additional behaviour. *

* Methods are forwarded directly to the decorated list. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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, Object object) { getList().add(index, object); } public boolean addAll(int index, Collection coll) { return getList().addAll(index, coll); } public Object 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 Object remove(int index) { return getList().remove(index); } public Object set(int index, Object object) { return getList().set(index, object); } public List subList(int fromIndex, int toIndex) { return getList().subList(fromIndex, toIndex); } } ././@LongLink0000000000000000000000000000016600000000000011570 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/list/AbstractSerializableListDecorator.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/list/AbstractSerializableL0000644000175000017500000000442210777673507032443 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.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 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(); } } ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/list/CursorableLinkedList.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/list/CursorableLinkedList.0000644000175000017500000005427610777673507032413 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.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.ArrayList; import java.util.Collection; import java.util.ConcurrentModificationException; import java.util.Iterator; import java.util.List; import java.util.ListIterator; /** * 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. * * @see java.util.LinkedList * @since Commons Collections 1.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Rodney Waldhoff * @author Janek Bogucki * @author Simon Kitching * @author Stephen Colebourne */ 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, Object 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 = (WeakReference) 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); } //----------------------------------------------------------------------- /** * 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) { SubCursor cursor = new SubCursor(subList, fromIndex); registerCursor(cursor); return cursor; } //----------------------------------------------------------------------- /** * 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; /** Flag to indicate if the current element was removed by another object. */ boolean currentRemovedByAnother = false; /** * Constructs a new cursor. * * @param index the index to start from */ protected Cursor(CursorableLinkedList parent, int index) { super(parent, index); valid = true; } /** * Removes the item last returned by this iterator. *

* There may have been subsequent alterations to the list * since you obtained this item, however you can still remove it. * You can even remove it if the item is no longer in the main list. * However, you can't call this method on the same iterator more * than once without calling next() or previous(). * * @throws IllegalStateException if there is no item to remove */ public void remove() { // overridden, as the nodeRemoved() method updates the iterator // state in the parent.removeNode() call below if (current == null && currentRemovedByAnother) { // quietly ignore, as the last returned node was removed // by the list or some other iterator // by ignoring it, we keep this iterator independent from // other changes as much as possible } else { checkModCount(); parent.removeNode(getLastNodeReturned()); } currentRemovedByAnother = false; } /** * 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(Object obj) { // overridden, as the nodeInserted() method updates the iterator state super.add(obj); // matches the (next.previous == node) clause in nodeInserted() // thus next gets changed - reset it again here next = next.next; } // set is not overridden, as it works ok // note that we want it to throw an exception if the element being // set has been removed from the real list (compare this with the // remove method where we silently ignore this case) /** * 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 && node == current) { // state where next() followed by previous() next = node.next; current = null; currentRemovedByAnother = true; } else if (node == next) { // state where next() not followed by previous() // and we are matching next node next = node.next; currentRemovedByAnother = false; } else if (node == current) { // state where next() not followed by previous() // and we are matching current (last returned) node current = null; currentRemovedByAnother = true; nextIndex--; } else { nextIndexValid = false; currentRemovedByAnother = 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; } } } //----------------------------------------------------------------------- /** * A cursor for the sublist based on LinkedSubListIterator. * * @since Commons Collections 3.2 */ protected static class SubCursor extends Cursor { /** The parent list */ protected final LinkedSubList sub; /** * Constructs a new cursor. * * @param index the index to start from */ protected SubCursor(LinkedSubList sub, int index) { super((CursorableLinkedList) sub.parent, index + 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(Object obj) { super.add(obj); sub.expectedModCount = parent.modCount; sub.size++; } public void remove() { super.remove(); sub.expectedModCount = parent.modCount; sub.size--; } } } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/list/FixedSizeList.java0000644000175000017500000001231610777673507031704 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.list; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import org.apache.commons.collections.BoundedCollection; import org.apache.commons.collections.iterators.AbstractListIteratorDecorator; import org.apache.commons.collections.iterators.UnmodifiableIterator; /** * 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. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne * @author Paul Jack */ 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(Object object) { throw new UnsupportedOperationException("List is fixed size"); } public void add(int index, Object 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 Object 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 Object 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 Object set(int index, Object 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(Object object) { throw new UnsupportedOperationException("List is fixed size"); } } public boolean isFull() { return true; } public int maxSize() { return size(); } } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/list/GrowthList.java0000644000175000017500000001703110777673507031263 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.list; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; /** * Decorates another List to make it seamlessly grow when * indices larger than the list size are used on add and set, * avoiding most IndexOutOfBoundsExceptions. *

* This class avoids errors by growing when a set or add method would * normally throw an IndexOutOfBoundsException. * Note that IndexOutOfBoundsException IS returned for invalid negative indices. *

* Trying to set or add to an index larger than the size will cause the list * to grow (using null elements). Clearly, care must be taken * not to use excessively large indices, as the internal list will grow to * match. *

* Trying to use any method other than add or set with an invalid index will * call the underlying list and probably result in an IndexOutOfBoundsException. *

* Take care when using this list with null values, as * null is the value added when growing the list. *

* All sub-lists will access the underlying list directly, and will throw * IndexOutOfBoundsExceptions. *

* This class differs from {@link LazyList} because here growth occurs on * set and add, where LazyList grows on get. However, they * can be used together by decorating twice. * * @see LazyList * @since Commons Collections 3.2 * @version $Revision: 155406 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne * @author Paul Legato */ public class GrowthList extends AbstractSerializableListDecorator { /** Serialization version */ private static final long serialVersionUID = -3620001881672L; /** * Factory method to create a growth 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 GrowthList(list); } //----------------------------------------------------------------------- /** * Constructor that uses an ArrayList internally. */ public GrowthList() { super(new ArrayList()); } /** * Constructor that uses an ArrayList internally. * * @param initialSize the initial size of the ArrayList * @throws IllegalArgumentException if initial size is invalid */ public GrowthList(int initialSize) { super(new ArrayList(initialSize)); } /** * Constructor that wraps (not copies). * * @param list the list to decorate, must not be null * @throws IllegalArgumentException if list is null */ protected GrowthList(List list) { super(list); } //----------------------------------------------------------------------- /** * Decorate the add method to perform the growth behaviour. *

* If the requested index is greater than the current size, the list will * grow to the new size. Indices between the old size and the requested * size will be filled with null. *

* If the index is less than the current size, the value will be added to * the underlying list directly. * If the index is less than zero, the underlying list is called, which * will probably throw an IndexOutOfBoundsException. * * @param index the index to add at * @param element the object to add at the specified index * @throws UnsupportedOperationException if the underlying list doesn't implement set * @throws ClassCastException if the underlying list rejects the element * @throws IllegalArgumentException if the underlying list rejects the element */ public void add(int index, Object element) { int size = getList().size(); if (index > size) { getList().addAll(Collections.nCopies(index - size, null)); } getList().add(index, element); } //----------------------------------------------------------------------- /** * Decorate the addAll method to perform the growth behaviour. *

* If the requested index is greater than the current size, the list will * grow to the new size. Indices between the old size and the requested * size will be filled with null. *

* If the index is less than the current size, the values will be added to * the underlying list directly. * If the index is less than zero, the underlying list is called, which * will probably throw an IndexOutOfBoundsException. * * @param index the index to add at * @param coll the collection to add at the specified index * @return true if the list changed * @throws UnsupportedOperationException if the underlying list doesn't implement set * @throws ClassCastException if the underlying list rejects the element * @throws IllegalArgumentException if the underlying list rejects the element */ public boolean addAll(int index, Collection coll) { int size = getList().size(); boolean result = false; if (index > size) { getList().addAll(Collections.nCopies(index - size, null)); result = true; } return (getList().addAll(index, coll) | result); } //----------------------------------------------------------------------- /** * Decorate the set method to perform the growth behaviour. *

* If the requested index is greater than the current size, the list will * grow to the new size. Indices between the old size and the requested * size will be filled with null. *

* If the index is less than the current size, the value will be set onto * the underlying list directly. * If the index is less than zero, the underlying list is called, which * will probably throw an IndexOutOfBoundsException. * * @param index the index to set * @param element the object to set at the specified index * @return the object previously at that index * @throws UnsupportedOperationException if the underlying list doesn't implement set * @throws ClassCastException if the underlying list rejects the element * @throws IllegalArgumentException if the underlying list rejects the element */ public Object set(int index, Object element) { int size = getList().size(); if (index >= size) { getList().addAll(Collections.nCopies((index - size) + 1, null)); } return getList().set(index, element); } } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/list/LazyList.java0000644000175000017500000001240510777673507030730 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.list; import java.util.List; import org.apache.commons.collections.Factory; /** * 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 differs from {@link GrowthList} because here growth occurs on * get, where GrowthList grows on set and add. However, they * could easily be used together by decorating twice. *

* This class is Serializable from Commons Collections 3.1. * * @see GrowthList * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne * @author Arron Bates * @author Paul Jack */ 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 Object get(int index) { int size = getList().size(); if (index < size) { // within bounds, get the object Object 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 Object 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); } } ././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/list/NodeCachingLinkedList.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/list/NodeCachingLinkedList0000644000175000017500000002012610777673507032361 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.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. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Jeff Varszegi * @author Rich Dougherty * @author Phil Steitz * @author Stephen Colebourne */ public class NodeCachingLinkedList extends AbstractLinkedList implements Serializable { /** Serialization version */ private 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(Object 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); } } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/list/package.html0000644000175000017500000000415310777673507030574 0ustar godgod

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 the 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
  • Growth - grows the list instead of erroring when set/add used with index beyond the list size
  • SetUnique - a list that avoids duplicate entries like a Set

libcommons-collections3-java.orig/src/java/org/apache/commons/collections/list/PredicatedList.java0000644000175000017500000001264110777673507032057 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.list; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import org.apache.commons.collections.Predicate; import org.apache.commons.collections.collection.PredicatedCollection; import org.apache.commons.collections.iterators.AbstractListIteratorDecorator; /** * 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. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne * @author Paul Jack */ 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 Object 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) { 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 Object set(int index, Object 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(Object object) { validate(object); iterator.add(object); } public void set(Object object) { validate(object); iterator.set(object); } } } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/list/SetUniqueList.java0000644000175000017500000002623410777673507031740 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.list; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.Set; import org.apache.commons.collections.iterators.AbstractIteratorDecorator; import org.apache.commons.collections.iterators.AbstractListIteratorDecorator; import org.apache.commons.collections.set.UnmodifiableSet; /** * 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. * Bear in mind that Sets require immutable objects to function correctly. *

* The {@link org.apache.commons.collections.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. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Matthew Hawthorne * @author Stephen Colebourne * @author Tom Dunham */ 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(Object 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, Object 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(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. * * @param index the index to insert at * @param object the object to set * @return the previous object */ public Object set(int index, Object object) { int pos = indexOf(object); Object removed = super.set(index, object); if (pos == -1 || pos == index) { return removed; } // the object is already in the uniq list // (and it hasn't been swapped with itself) super.remove(pos); // remove the duplicate by index set.remove(removed); // remove the item deleted by the set return removed; // return the item deleted by the set } public boolean remove(Object object) { boolean result = super.remove(object); set.remove(object); return result; } public Object remove(int index) { Object 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 Object last = null; protected SetListIterator(Iterator it, Set set) { super(it); this.set = set; } public Object 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 Object last = null; protected SetListListIterator(ListIterator it, Set set) { super(it); this.set = set; } public Object next() { last = super.next(); return last; } public Object previous() { last = super.previous(); return last; } public void remove() { super.remove(); set.remove(last); last = null; } public void add(Object object) { if (set.contains(object) == false) { super.add(object); set.add(object); } } public void set(Object object) { throw new UnsupportedOperationException("ListIterator does not support set"); } } } ././@LongLink0000000000000000000000000000014500000000000011565 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/list/SynchronizedList.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/list/SynchronizedList.java0000644000175000017500000001172010777673507032467 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.list; import java.util.Collection; import java.util.List; import java.util.ListIterator; import org.apache.commons.collections.collection.SynchronizedCollection; /** * 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. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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, Object object) { synchronized (lock) { getList().add(index, object); } } public boolean addAll(int index, Collection coll) { synchronized (lock) { return getList().addAll(index, coll); } } public Object 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 Object remove(int index) {
        synchronized (lock) {
            return getList().remove(index);
        }
    }

    public Object set(int index, Object 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);
        }
    }

}
libcommons-collections3-java.orig/src/java/org/apache/commons/collections/list/TransformedList.java0000644000175000017500000001206010777673507032272 0ustar  godgod/*
 *  Licensed to the Apache Software Foundation (ASF) under one or more
 *  contributor license agreements.  See the NOTICE file distributed with
 *  this work for additional information regarding copyright ownership.
 *  The ASF licenses this file to You under the Apache License, Version 2.0
 *  (the "License"); you may not use this file except in compliance with
 *  the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package org.apache.commons.collections.list;

import java.util.Collection;
import java.util.List;
import java.util.ListIterator;

import org.apache.commons.collections.Transformer;
import org.apache.commons.collections.collection.TransformedCollection;
import org.apache.commons.collections.iterators.AbstractListIteratorDecorator;

/**
 * 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. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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 Object 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) { object = transform(object); getList().add(index, object); } public boolean addAll(int index, Collection coll) { coll = transform(coll); return getList().addAll(index, coll); } public ListIterator listIterator() { return listIterator(0); } public ListIterator listIterator(int i) { return new TransformedListIterator(getList().listIterator(i)); } public Object set(int index, Object object) { object = transform(object); return getList().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) { object = transform(object); iterator.add(object); } public void set(Object object) { object = transform(object); iterator.set(object); } } } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/list/TreeList.java0000644000175000017500000007421510777673507030717 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.list; import java.util.AbstractList; import java.util.Collection; import java.util.ConcurrentModificationException; import java.util.Iterator; import java.util.ListIterator; import java.util.NoSuchElementException; import org.apache.commons.collections.OrderedIterator; /** * 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. * * @since Commons Collections 3.1 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Joerg Schmuecker * @author Stephen Colebourne */ 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 Object 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(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(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, Object 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 Object set(int index, Object obj) { checkInterval(index, 0, size() - 1); AVLNode node = root.get(index); Object 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 Object remove(int index) { modCount++; checkInterval(index, 0, size() - 1); Object 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 Object 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, Object 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 */ Object getValue() { return value; } /** * Sets the value. * * @param obj the value to store */ void setValue(Object 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(Object 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(Object[] 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, Object obj) { int indexRelativeToMe = index - relativePosition; if (indexRelativeToMe <= 0) { return insertOnLeft(indexRelativeToMe, obj); } else { return insertOnRight(indexRelativeToMe, obj); } } private AVLNode insertOnLeft(int indexRelativeToMe, Object 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, Object 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(); } /** * Removes this node from the tree. * * @return the node that replaces this one in the parent */ 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) { // more on the right, so delete from the right AVLNode rightMin = right.min(); value = rightMin.value; if (leftIsPrevious) { left = rightMin.left; } right = right.removeMin(); if (relativePosition < 0) { relativePosition++; } } else { // more on the left or equal, so delete from the left AVLNode leftMax = left.max(); value = leftMax.value; if (rightIsNext) { right = leftMax.right; } AVLNode leftPrevious = left.left; left = left.removeMax(); if (left == null) { // special case where left that was deleted was a double link // only occurs when height difference is equal left = leftPrevious; leftIsPrevious = true; } 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; } /** * Sets the left field to the node, or the previous node if that is null * * @param node the new left subtree node * @param previous the previous node in the linked list */ private void setLeft(AVLNode node, AVLNode previous) { leftIsPrevious = (node == null); left = (leftIsPrevious ? previous : node); recalcHeight(); } /** * Sets the right field to the node, or the next node if that is null * * @param node the new left subtree node * @param next the next node in the linked list */ 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; /** * Cache of the next node that will be returned by {@link #next()}. */ protected AVLNode next; /** * The index of the next node to be returned. */ protected int nextIndex; /** * Cache of the last node that was returned by {@link #next()} * or {@link #previous()}. */ protected AVLNode current; /** * The index of the last node that was returned. */ 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; this.currentIndex = -1; } /** * 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 Object next() { checkModCount(); if (!hasNext()) { throw new NoSuchElementException("No element at index " + nextIndex + "."); } if (next == null) { next = parent.root.get(nextIndex); } Object value = next.getValue(); current = next; currentIndex = nextIndex++; next = next.next(); return value; } public boolean hasPrevious() { return (nextIndex > 0); } public Object 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(); } Object 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 (currentIndex == -1) { throw new IllegalStateException(); } if (nextIndex == currentIndex) { // remove() following previous() next = next.next(); parent.remove(currentIndex); } else { // remove() following next() parent.remove(currentIndex); nextIndex--; } current = null; currentIndex = -1; expectedModCount++; } public void set(Object obj) { checkModCount(); if (current == null) { throw new IllegalStateException(); } current.setValue(obj); } public void add(Object obj) { checkModCount(); parent.add(nextIndex, obj); current = null; currentIndex = -1; nextIndex++; expectedModCount++; } } } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/list/TypedList.java0000644000175000017500000000426310777673507031101 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.list; import java.util.List; import org.apache.commons.collections.functors.InstanceofPredicate; /** * 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. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne * @author Matthew Hawthorne */ 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() { } } ././@LongLink0000000000000000000000000000014500000000000011565 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/list/UnmodifiableList.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/list/UnmodifiableList.java0000644000175000017500000001021710777673507032406 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.list; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import org.apache.commons.collections.Unmodifiable; import org.apache.commons.collections.iterators.UnmodifiableIterator; import org.apache.commons.collections.iterators.UnmodifiableListIterator; /** * Decorates another List to ensure it can't be altered. *

* This class is Serializable from Commons Collections 3.1. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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(Object 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, Object object) { throw new UnsupportedOperationException(); } public boolean addAll(int index, Collection coll) { throw new UnsupportedOperationException(); } public Object remove(int index) { throw new UnsupportedOperationException(); } public Object set(int index, Object object) { throw new UnsupportedOperationException(); } public List subList(int fromIndex, int toIndex) { List sub = getList().subList(fromIndex, toIndex); return new UnmodifiableList(sub); } } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/map/0000755000175000017500000000000011010124151026051 5ustar godgod././@LongLink0000000000000000000000000000014500000000000011565 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/map/AbstractHashedMap.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/map/AbstractHashedMap.java0000644000175000017500000013126010777673462032276 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.map; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.AbstractCollection; import java.util.AbstractMap; import java.util.AbstractSet; import java.util.Collection; import java.util.ConcurrentModificationException; import java.util.Iterator; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; import org.apache.commons.collections.IterableMap; import org.apache.commons.collections.KeyValue; import org.apache.commons.collections.MapIterator; import org.apache.commons.collections.iterators.EmptyIterator; import org.apache.commons.collections.iterators.EmptyMapIterator; /** * 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. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author java util HashMap * @author Stephen Colebourne * @author Christian Siefkes */ 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; initialCapacity = calculateNewCapacity(initialCapacity); this.threshold = calculateThreshold(initialCapacity, loadFactor); 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 Object get(Object key) { key = convertKey(key); int hashCode = hash(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) { key = convertKey(key); int hashCode = hash(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 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 Object put(Object key, Object value) { key = convertKey(key); int hashCode = hash(key); int index = hashIndex(hashCode, data.length); HashEntry entry = data[index]; while (entry != null) { if (entry.hashCode == hashCode && isEqualKey(key, entry.key)) { Object 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)); 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 Object remove(Object key) { key = convertKey(key); int hashCode = hash(key); int index = hashIndex(hashCode, data.length); HashEntry entry = data[index]; HashEntry previous = null; while (entry != null) { if (entry.hashCode == hashCode && isEqualKey(key, entry.key)) { Object 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; } //----------------------------------------------------------------------- /** * Converts input keys to another object for storage in the map. * This implementation masks nulls. * Subclasses can override this to perform alternate key conversions. *

* The reverse conversion can be changed, if required, by overriding the * getKey() method in the hash entry. * * @param key the key convert * @return the converted key */ protected Object convertKey(Object key) { return (key == null ? NULL : key); } /** * 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 and assumes neither key is null. * 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.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) { key = convertKey(key); int hashCode = hash(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; } 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, Object 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, Object key, Object 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, Object key, Object 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, Object key, Object 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 Object 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 Object 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 Object next() { return super.nextEntry().getKey(); } public Object getKey() { HashEntry current = currentEntry(); if (current == null) { throw new IllegalStateException(AbstractHashedMap.GETKEY_INVALID); } return current.getKey(); } public Object getValue() { HashEntry current = currentEntry(); if (current == null) { throw new IllegalStateException(AbstractHashedMap.GETVALUE_INVALID); } return current.getValue(); } public Object setValue(Object 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(Object entry) { if (entry instanceof Map.Entry) { Map.Entry e = (Map.Entry) entry; Entry match = parent.getEntry(e.getKey()); return (match != null && match.equals(e)); } return false; } 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; Object key = entry.getKey(); parent.remove(key); return true; } public Iterator iterator() { return parent.createEntrySetIterator(); } } /** * EntrySet iterator. */ protected static class EntrySetIterator extends HashIterator { protected EntrySetIterator(AbstractHashedMap parent) { super(parent); } public Object 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 EntrySetIterator { protected KeySetIterator(AbstractHashedMap parent) { super(parent); } public Object 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 { protected ValuesIterator(AbstractHashedMap parent) { super(parent); } public Object 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 */ protected Object key; /** The value */ protected Object value; protected HashEntry(HashEntry next, int hashCode, Object key, Object value) { super(); this.next = next; this.hashCode = hashCode; this.key = key; this.value = value; } public Object getKey() { return (key == NULL ? null : key); } public Object getValue() { return value; } public Object setValue(Object value) { Object 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 implements Iterator { /** 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(); threshold = calculateThreshold(capacity, loadFactor); data = new HashEntry[capacity]; for (int i = 0; i < size; i++) { Object key = in.readObject(); Object value = in.readObject(); put(key, value); } } //----------------------------------------------------------------------- /** * 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(); } } ././@LongLink0000000000000000000000000000016400000000000011566 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/map/AbstractInputCheckedMapDecorator.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/map/AbstractInputCheckedMa0000644000175000017500000001622010777673462032346 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.map; import java.lang.reflect.Array; import java.util.Iterator; import java.util.Map; import java.util.Set; import org.apache.commons.collections.iterators.AbstractIteratorDecorator; import org.apache.commons.collections.keyvalue.AbstractMapEntryDecorator; import org.apache.commons.collections.set.AbstractSetDecorator; /** * 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. * * @since Commons Collections 3.1 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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 Object checkSetValue(Object 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. * * @return true always */ 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 Object[] toArray(Object 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 = (Object[]) 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 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 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 Object next() { Map.Entry entry = (Map.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 Object setValue(Object value) { value = parent.checkSetValue(value); return entry.setValue(value); } } } ././@LongLink0000000000000000000000000000014500000000000011565 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/map/AbstractLinkedMap.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/map/AbstractLinkedMap.java0000644000175000017500000005100610777673462032307 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.map; import java.util.ConcurrentModificationException; import java.util.Iterator; import java.util.Map; import java.util.NoSuchElementException; import org.apache.commons.collections.MapIterator; import org.apache.commons.collections.OrderedIterator; import org.apache.commons.collections.OrderedMap; import org.apache.commons.collections.OrderedMapIterator; import org.apache.commons.collections.ResettableIterator; import org.apache.commons.collections.iterators.EmptyOrderedIterator; import org.apache.commons.collections.iterators.EmptyOrderedMapIterator; /** * 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. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author java util LinkedHashMap * @author Stephen Colebourne */ 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. *

* NOTE: As from v3.2 this method calls * {@link #createEntry(HashEntry, int, Object, Object)} to create * the map entry object. */ protected void init() { header = (LinkEntry) createEntry(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 Object 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 Object 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 Object nextKey(Object 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 Object previousKey(Object 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, Object key, Object 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 { protected LinkMapIterator(AbstractLinkedMap parent) { super(parent); } public Object next() { return super.nextEntry().getKey(); } public Object previous() { return super.previousEntry().getKey(); } public Object getKey() { HashEntry current = currentEntry(); if (current == null) { throw new IllegalStateException(AbstractHashedMap.GETKEY_INVALID); } return current.getKey(); } public Object getValue() { HashEntry current = currentEntry(); if (current == null) { throw new IllegalStateException(AbstractHashedMap.GETVALUE_INVALID); } return current.getValue(); } public Object setValue(Object 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 { protected EntrySetIterator(AbstractLinkedMap parent) { super(parent); } public Object next() { return super.nextEntry(); } public Object 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 EntrySetIterator { protected KeySetIterator(AbstractLinkedMap parent) { super(parent); } public Object next() { return super.nextEntry().getKey(); } public Object 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 { protected ValuesIterator(AbstractLinkedMap parent) { super(parent); } public Object next() { return super.nextEntry().getValue(); } public Object 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, Object key, Object value) { super(next, hashCode, key, value); } } /** * Base Iterator that iterates in link order. */ protected static abstract class LinkIterator implements OrderedIterator, ResettableIterator { /** 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[]"; } } } } ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/map/AbstractMapDecorator.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/map/AbstractMapDecorator.j0000644000175000017500000000755310777673462032343 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.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. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Daniel Rall * @author Stephen Colebourne */ 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 Object get(Object key) { return map.get(key); } public boolean isEmpty() { return map.isEmpty(); } public Set keySet() { return map.keySet(); } public Object put(Object key, Object value) { return map.put(key, value); } public void putAll(Map mapToCopy) { map.putAll(mapToCopy); } public Object 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(); } } ././@LongLink0000000000000000000000000000015700000000000011570 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/map/AbstractOrderedMapDecorator.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/map/AbstractOrderedMapDeco0000644000175000017500000000623610777673462032345 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.map; import org.apache.commons.collections.MapIterator; import org.apache.commons.collections.OrderedMap; import org.apache.commons.collections.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. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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 Object firstKey() { return getOrderedMap().firstKey(); } public Object lastKey() { return getOrderedMap().lastKey(); } public Object nextKey(Object key) { return getOrderedMap().nextKey(key); } public Object previousKey(Object key) { return getOrderedMap().previousKey(key); } public MapIterator mapIterator() { return getOrderedMap().mapIterator(); } public OrderedMapIterator orderedMapIterator() { return getOrderedMap().orderedMapIterator(); } } ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/map/AbstractReferenceMap.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/map/AbstractReferenceMap.j0000644000175000017500000010042310777673462032305 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.map; 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.ArrayList; import java.util.Collection; import java.util.ConcurrentModificationException; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; import org.apache.commons.collections.MapIterator; import org.apache.commons.collections.keyvalue.DefaultMapEntry; /** * 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. * * @see java.lang.ref.Reference * @since Commons Collections 3.1 (extracted from ReferenceMap in 3.0) * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Paul Jack * @author Stephen Colebourne */ 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 #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 */ 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 Object 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 Object put(Object key, Object 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 Object 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) { 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 */ protected HashEntry createEntry(HashEntry next, int hashCode, Object key, Object value) { return new ReferenceEntry(this, 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 Object[] toArray(Object[] arr) { // special implementation to handle disappearing entries ArrayList list = new ArrayList(); Iterator iterator = iterator(); while (iterator.hasNext()) { Entry e = (Entry) 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 Object[] toArray(Object[] 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 Object[] toArray(Object[] 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; /** * 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, HashEntry next, int hashCode, Object key, Object value) { super(next, hashCode, null, null); this.parent = parent; this.key = toReference(parent.keyType, key, hashCode); this.value = toReference(parent.valueType, value, hashCode); // the key hashCode is passed in deliberately } /** * 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 Object getKey() { return (parent.keyType > HARD) ? ((Reference) key).get() : key; } /** * 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 Object getValue() { return (parent.valueType > HARD) ? ((Reference) value).get() : value; } /** * Sets the value of the entry. * * @param obj the object to store * @return the previous value */ public Object setValue(Object obj) { Object old = getValue(); if (parent.valueType > HARD) { ((Reference)value).clear(); } value = toReference(parent.valueType, obj, hashCode); 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, key) && 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 Object toReference(int type, Object referent, int hash) { switch (type) { case HARD: return referent; case SOFT: return new SoftRef(hash, referent, parent.queue); case WEAK: return new WeakRef(hash, referent, parent.queue); default: throw new Error(); } } /** * Purges the specified reference * @param ref the reference to purge * @return true or false */ boolean purge(Reference ref) { boolean r = (parent.keyType > HARD) && (key == ref); r = r || ((parent.valueType > HARD) && (value == ref)); if (r) { if (parent.keyType > HARD) { ((Reference)key).clear(); } if (parent.valueType > HARD) { ((Reference)value).clear(); } else if (parent.purgeValues) { value = 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 ReferenceEntrySetIterator implements Iterator { /** 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. Object nextKey, nextValue; Object currentKey, currentValue; int expectedModCount; public ReferenceEntrySetIterator(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 Object next() { 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 keySet iterator. */ static class ReferenceKeySetIterator extends ReferenceEntrySetIterator { ReferenceKeySetIterator(AbstractReferenceMap parent) { super(parent); } public Object next() { return nextEntry().getKey(); } } /** * The values iterator. */ static class ReferenceValuesIterator extends ReferenceEntrySetIterator { ReferenceValuesIterator(AbstractReferenceMap parent) { super(parent); } public Object next() { return nextEntry().getValue(); } } /** * The MapIterator implementation. */ static class ReferenceMapIterator extends ReferenceEntrySetIterator implements MapIterator { protected ReferenceMapIterator(AbstractReferenceMap parent) { super(parent); } public Object next() { return nextEntry().getKey(); } public Object getKey() { HashEntry current = currentEntry(); if (current == null) { throw new IllegalStateException(AbstractHashedMap.GETKEY_INVALID); } return current.getKey(); } public Object getValue() { HashEntry current = currentEntry(); if (current == null) { throw new IllegalStateException(AbstractHashedMap.GETVALUE_INVALID); } return current.getValue(); } public Object setValue(Object 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, Object 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, Object 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) { Object key = in.readObject(); if (key == null) { break; } Object value = in.readObject(); put(key, value); } threshold = calculateThreshold(data.length, loadFactor); // do not call super.doReadObject() as code there doesn't work for reference map } } ././@LongLink0000000000000000000000000000015600000000000011567 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/map/AbstractSortedMapDecorator.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/map/AbstractSortedMapDecor0000644000175000017500000000606110777673463032400 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.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. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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 Object firstKey() { return getSortedMap().firstKey(); } public SortedMap headMap(Object toKey) { return getSortedMap().headMap(toKey); } public Object lastKey() { return getSortedMap().lastKey(); } public SortedMap subMap(Object fromKey, Object toKey) { return getSortedMap().subMap(fromKey, toKey); } public SortedMap tailMap(Object fromKey) { return getSortedMap().tailMap(fromKey); } } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/map/CaseInsensitiveMap.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/map/CaseInsensitiveMap.jav0000644000175000017500000001255010777673462032351 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.map; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.Map; /** * 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.toString().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}. *

* Note that CaseInsensitiveMap is not synchronized and is not thread-safe. * If you wish to use this map from multiple threads concurrently, you must use * appropriate synchronization. The simplest approach is to wrap this map * using {@link java.util.Collections#synchronizedMap(Map)}. This class may throw * exceptions when accessed by concurrent threads without synchronization. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Commons-Collections team */ 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); } //----------------------------------------------------------------------- /** * Overrides convertKey() from {@link AbstractHashedMap} to convert keys to * lower case. *

* Returns null if key is null. * * @param key the key convert * @return the converted key */ protected Object convertKey(Object key) { if (key != null) { return key.toString().toLowerCase(); } else { return AbstractHashedMap.NULL; } } //----------------------------------------------------------------------- /** * 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); } } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/map/CompositeMap.java0000644000175000017500000005570710777673462031373 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.map; import java.util.Collection; import java.util.Iterator; import java.util.Map; import java.util.Set; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.collection.CompositeCollection; import org.apache.commons.collections.set.CompositeSet; /** * 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. *

* Note that CompositeMap is not synchronized and is not thread-safe. * If you wish to use this map from multiple threads concurrently, you must use * appropriate synchronization. The simplest approach is to wrap this map * using {@link java.util.Collections#synchronizedMap(Map)}. This class may throw * exceptions when accessed by concurrent threads without synchronization. * * @since Commons Collections 3.0 * @version $Revision: 647116 $ $Date: 2008-04-11 12:23:08 +0100 (Fri, 11 Apr 2008) $ * * @author Brian McCallister */ 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 = 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. * * @see CompositeSet * @return a set view of the mappings contained in this map. */ 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 Object get(Object key) { for (int i = this.composite.length - 1; i >= 0; --i) { if (this.composite[i].containsKey(key)) { return 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 Object put(Object key, Object 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 Object remove(Object key) { for (int i = this.composite.length - 1; i >= 0; --i) { if (this.composite[i].containsKey(key)) { return 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 Object put(CompositeMap map, Map[] composited, Object key, Object 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); } } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/map/DefaultedMap.java0000644000175000017500000001652510777673463031322 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.map; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.HashMap; import java.util.Map; import org.apache.commons.collections.Factory; import org.apache.commons.collections.Transformer; import org.apache.commons.collections.functors.ConstantTransformer; import org.apache.commons.collections.functors.FactoryTransformer; /** * Decorates another Map returning a default value if the map * does not contain the requested key. *

* When the {@link #get(Object)} method is called with a key that does not * exist in the map, this map will return the default value specified in * the constructor/factory. Only the get method is altered, so the * {@link Map#containsKey(Object)} can be used to determine if a key really * is in the map or not. *

* The defaulted value is not added to the map. * Compare this behaviour with {@link LazyMap}, which does add the value * to the map (via a Transformer). *

* For instance: *

 * Map map = new DefaultedMap("NULL");
 * Object obj = map.get("Surname");
 * // obj == "NULL"
 * 
* After the above code is executed the map is still empty. *

* Note that DefaultedMap is not synchronized and is not thread-safe. * If you wish to use this map from multiple threads concurrently, you must use * appropriate synchronization. The simplest approach is to wrap this map * using {@link java.util.Collections#synchronizedMap(Map)}. This class may throw * exceptions when accessed by concurrent threads without synchronization. * * @since Commons Collections 3.2 * @version $Revision: 1.7 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne * @author Rafael U.C. Afonso * @see LazyMap */ public class DefaultedMap extends AbstractMapDecorator implements Map, Serializable { /** Serialization version */ private static final long serialVersionUID = 19698628745827L; /** The transformer to use if the map does not contain a key */ protected final Object value; //----------------------------------------------------------------------- /** * Factory method to create a defaulting map. *

* The value specified is returned when a missing key is found. * * @param map the map to decorate, must not be null * @param defaultValue the default value to return when the key is not found * @throws IllegalArgumentException if map is null */ public static Map decorate(Map map, Object defaultValue) { if (defaultValue instanceof Transformer) { defaultValue = ConstantTransformer.getInstance(defaultValue); } return new DefaultedMap(map, defaultValue); } /** * Factory method to create a defaulting map. *

* The factory specified is called when a missing key is found. * The result will be returned as the result of the map get(key) method. * * @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) { if (factory == null) { throw new IllegalArgumentException("Factory must not be null"); } return new DefaultedMap(map, FactoryTransformer.getInstance(factory)); } /** * Factory method to create a defaulting map. *

* The transformer specified is called when a missing key is found. * The key is passed to the transformer as the input, and the result * will be returned as the result of the map get(key) method. * * @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, Transformer factory) { if (factory == null) { throw new IllegalArgumentException("Transformer must not be null"); } return new DefaultedMap(map, factory); } //----------------------------------------------------------------------- /** * Constructs a new empty DefaultedMap that decorates * a HashMap. *

* The object passed in will be returned by the map whenever an * unknown key is requested. * * @param defaultValue the default value to return when the key is not found */ public DefaultedMap(Object defaultValue) { super(new HashMap()); if (defaultValue instanceof Transformer) { defaultValue = ConstantTransformer.getInstance(defaultValue); } this.value = defaultValue; } /** * Constructor that wraps (not copies). * * @param map the map to decorate, must not be null * @param value the value to use * @throws IllegalArgumentException if map or transformer is null */ protected DefaultedMap(Map map, Object value) { super(map); this.value = value; } //----------------------------------------------------------------------- /** * Write the map out using a custom routine. * * @param out the output stream * @throws IOException */ 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 */ private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); map = (Map) in.readObject(); } //----------------------------------------------------------------------- public Object get(Object key) { // create value for key if key is not currently in the map if (map.containsKey(key) == false) { if (value instanceof Transformer) { return ((Transformer) value).transform(key); } 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. } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/map/FixedSizeMap.java0000644000175000017500000001311110777673463031303 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.map; 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; import org.apache.commons.collections.BoundedMap; import org.apache.commons.collections.collection.UnmodifiableCollection; import org.apache.commons.collections.set.UnmodifiableSet; /** * 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. *

* Note that FixedSizeMap is not synchronized and is not thread-safe. * If you wish to use this map from multiple threads concurrently, you must use * appropriate synchronization. The simplest approach is to wrap this map * using {@link java.util.Collections#synchronizedMap(Map)}. This class may throw * exceptions when accessed by concurrent threads without synchronization. *

* This class is Serializable from Commons Collections 3.1. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne * @author Paul Jack */ 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 Object put(Object key, Object 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 Object 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(); } } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/map/FixedSizeSortedMap.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/map/FixedSizeSortedMap.jav0000644000175000017500000001407710777673462032336 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.map; 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; import java.util.SortedMap; import org.apache.commons.collections.BoundedMap; import org.apache.commons.collections.collection.UnmodifiableCollection; import org.apache.commons.collections.set.UnmodifiableSet; /** * 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. *

* Note that FixedSizeSortedMap is not synchronized and is not thread-safe. * If you wish to use this map from multiple threads concurrently, you must use * appropriate synchronization. The simplest approach is to wrap this map * using {@link java.util.Collections#synchronizedSortedMap}. This class may throw * exceptions when accessed by concurrent threads without synchronization. *

* This class is Serializable from Commons Collections 3.1. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne * @author Paul Jack */ 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 Object put(Object key, Object 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 Object 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(Object fromKey, Object toKey) { SortedMap map = getSortedMap().subMap(fromKey, toKey); return new FixedSizeSortedMap(map); } public SortedMap headMap(Object toKey) { SortedMap map = getSortedMap().headMap(toKey); return new FixedSizeSortedMap(map); } public SortedMap tailMap(Object fromKey) { SortedMap map = getSortedMap().tailMap(fromKey); return new FixedSizeSortedMap(map); } public boolean isFull() { return true; } public int maxSize() { return size(); } } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/map/Flat3Map.java0000644000175000017500000011035410777673462030370 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.map; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.AbstractCollection; import java.util.AbstractSet; import java.util.Collection; import java.util.Iterator; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; import org.apache.commons.collections.IterableMap; import org.apache.commons.collections.MapIterator; import org.apache.commons.collections.ResettableIterator; import org.apache.commons.collections.iterators.EmptyIterator; import org.apache.commons.collections.iterators.EmptyMapIterator; /** * 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. *

* Note that Flat3Map is not synchronized and is not thread-safe. * If you wish to use this map from multiple threads concurrently, you must use * appropriate synchronization. The simplest approach is to wrap this map * using {@link java.util.Collections#synchronizedMap(Map)}. This class may throw * exceptions when accessed by concurrent threads without synchronization. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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 Object key1; /** Key, used while in flat mode */ private transient Object key2; /** Key, used while in flat mode */ private transient Object key3; /** Value, used while in flat mode */ private transient Object value1; /** Value, used while in flat mode */ private transient Object value2; /** Value, used while in flat mode */ private transient Object 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 Object 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 Object put(Object key, Object value) { if (delegateMap != null) { return delegateMap.put(key, value); } // change existing mapping if (key == null) { switch (size) { // drop through case 3: if (key3 == null) { Object old = value3; value3 = value; return old; } case 2: if (key2 == null) { Object old = value2; value2 = value; return old; } case 1: if (key1 == null) { Object 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)) { Object old = value3; value3 = value; return old; } case 2: if (hash2 == hashCode && key.equals(key2)) { Object old = value2; value2 = value; return old; } case 1: if (hash1 == hashCode && key.equals(key1)) { Object 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 Object 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) { Object old = value3; hash3 = 0; key3 = null; value3 = null; size = 2; return old; } if (key2 == null) { Object old = value3; hash2 = hash3; key2 = key3; value2 = value3; hash3 = 0; key3 = null; value3 = null; size = 2; return old; } if (key1 == null) { Object 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) { Object old = value2; hash2 = 0; key2 = null; value2 = null; size = 1; return old; } if (key1 == null) { Object 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) { Object 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)) { Object old = value3; hash3 = 0; key3 = null; value3 = null; size = 2; return old; } if (hash2 == hashCode && key.equals(key2)) { Object old = value3; hash2 = hash3; key2 = key3; value2 = value3; hash3 = 0; key3 = null; value3 = null; size = 2; return old; } if (hash1 == hashCode && key.equals(key1)) { Object 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)) { Object old = value2; hash2 = 0; key2 = null; value2 = null; size = 1; return old; } if (hash1 == hashCode && key.equals(key1)) { Object 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)) { Object 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 Object 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 Object 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 Object 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 Object setValue(Object value) { if (canRemove == false) { throw new IllegalStateException(AbstractHashedMap.SETVALUE_INVALID); } Object 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); } } /** * EntrySetIterator and MapEntry */ static class EntrySetIterator implements Iterator, Map.Entry { private final Flat3Map parent; private int nextIndex = 0; private boolean canRemove = false; EntrySetIterator(Flat3Map parent) { super(); this.parent = parent; } public boolean hasNext() { return (nextIndex < parent.size); } public Object next() { if (hasNext() == false) { throw new NoSuchElementException(AbstractHashedMap.NO_NEXT_ENTRY); } canRemove = true; nextIndex++; return this; } public void remove() { if (canRemove == false) { throw new IllegalStateException(AbstractHashedMap.REMOVE_INVALID); } parent.remove(getKey()); nextIndex--; canRemove = false; } public Object 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 Object 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 Object setValue(Object value) { if (canRemove == false) { throw new IllegalStateException(AbstractHashedMap.SETVALUE_INVALID); } Object 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 EntrySetIterator { KeySetIterator(Flat3Map parent) { super(parent); } public Object next() { super.next(); 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 EntrySetIterator { ValuesIterator(Flat3Map parent) { super(parent); } public Object next() { super.next(); 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(in.readObject(), 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) { return false; } otherValue = other.get(key3); if (value3 == null ? otherValue != null : !value3.equals(otherValue)) { return false; } case 2: if (other.containsKey(key2) == false) { return false; } otherValue = other.get(key2); if (value2 == null ? otherValue != null : !value2.equals(otherValue)) { return false; } case 1: if (other.containsKey(key1) == false) { return 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 == this ? "(this Map)" : key3)); buf.append('='); buf.append((value3 == this ? "(this Map)" : value3)); buf.append(','); case 2: buf.append((key2 == this ? "(this Map)" : key2)); buf.append('='); buf.append((value2 == this ? "(this Map)" : value2)); buf.append(','); case 1: buf.append((key1 == this ? "(this Map)" : key1)); buf.append('='); buf.append((value1 == this ? "(this Map)" : value1)); } buf.append('}'); return buf.toString(); } } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/map/HashedMap.java0000644000175000017500000001000410777673462030602 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.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.collections.MapIterator MapIterator} * functionality and many methods for subclassing. *

* Note that HashedMap is not synchronized and is not thread-safe. * If you wish to use this map from multiple threads concurrently, you must use * appropriate synchronization. The simplest approach is to wrap this map * using {@link java.util.Collections#synchronizedMap(Map)}. This class may throw * exceptions when accessed by concurrent threads without synchronization. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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); } } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/map/IdentityMap.java0000644000175000017500000001502110777673462031203 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.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. *

* Note that IdentityMap is not synchronized and is not thread-safe. * If you wish to use this map from multiple threads concurrently, you must use * appropriate synchronization. The simplest approach is to wrap this map * using {@link java.util.Collections#synchronizedMap(Map)}. This class may throw * exceptions when accessed by concurrent threads without synchronization. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author java util HashMap * @author Stephen Colebourne */ 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, Object key, Object value) { return new IdentityEntry(next, hashCode, key, value); } //----------------------------------------------------------------------- /** * HashEntry */ protected static class IdentityEntry extends HashEntry { protected IdentityEntry(HashEntry next, int hashCode, Object key, Object 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); } } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/map/LazyMap.java0000644000175000017500000001377310777673462030345 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.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.collections.Factory; import org.apache.commons.collections.Transformer; import org.apache.commons.collections.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. *

* Note that LazyMap is not synchronized and is not thread-safe. * If you wish to use this map from multiple threads concurrently, you must use * appropriate synchronization. The simplest approach is to wrap this map * using {@link java.util.Collections#synchronizedMap(Map)}. This class may throw * exceptions when accessed by concurrent threads without synchronization. *

* This class is Serializable from Commons Collections 3.1. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne * @author Paul Jack */ 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 Transformer factory; /** * 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 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, Transformer factory) { return new LazyMap(map, factory); } //----------------------------------------------------------------------- /** * 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.factory = FactoryTransformer.getInstance(factory); } /** * 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, Transformer factory) { super(map); if (factory == null) { throw new IllegalArgumentException("Factory must not be null"); } this.factory = factory; } //----------------------------------------------------------------------- /** * 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 Object get(Object key) { // create value for key if key is not currently in the map if (map.containsKey(key) == false) { Object value = factory.transform(key); map.put(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. } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/map/LazySortedMap.java0000644000175000017500000001244410777673462031520 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.map; import java.util.Comparator; import java.util.SortedMap; import org.apache.commons.collections.Factory; import org.apache.commons.collections.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. *

* Note that LazySortedMap is not synchronized and is not thread-safe. * If you wish to use this map from multiple threads concurrently, you must use * appropriate synchronization. The simplest approach is to wrap this map * using {@link java.util.Collections#synchronizedSortedMap}. This class may throw * exceptions when accessed by concurrent threads without synchronization. *

* This class is Serializable from Commons Collections 3.1. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne * @author Paul Jack */ 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 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, Transformer factory) { return new LazySortedMap(map, factory); } //----------------------------------------------------------------------- /** * 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 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, Transformer factory) { super(map, factory); } //----------------------------------------------------------------------- /** * 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 LazySortedMap(map, factory); } public SortedMap headMap(Object toKey) { SortedMap map = getSortedMap().headMap(toKey); return new LazySortedMap(map, factory); } public SortedMap tailMap(Object fromKey) { SortedMap map = getSortedMap().tailMap(fromKey); return new LazySortedMap(map, factory); } } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/map/LinkedMap.java0000644000175000017500000002323710777673462030630 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.map; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.AbstractList; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.Map; import org.apache.commons.collections.iterators.UnmodifiableIterator; import org.apache.commons.collections.iterators.UnmodifiableListIterator; import org.apache.commons.collections.list.UnmodifiableList; /** * 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.collections.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. *

* Note that LinkedMap is not synchronized and is not thread-safe. * If you wish to use this map from multiple threads concurrently, you must use * appropriate synchronization. The simplest approach is to wrap this map * using {@link java.util.Collections#synchronizedMap(Map)}. This class may throw * exceptions when accessed by concurrent threads without synchronization. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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 Object 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 Object 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) { key = convertKey(key); int i = 0; for (LinkEntry entry = header.after; entry != header; entry = entry.after, i++) { if (isEqualKey(key, entry.key)) { 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 Object 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()}. * * @see #keySet() * @return The ordered list of keys. */ 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 Object 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 Object 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 Object[] toArray(Object[] 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)); } } } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/map/ListOrderedMap.java0000644000175000017500000005477610777673462031656 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.map; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.AbstractList; import java.util.AbstractSet; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; import org.apache.commons.collections.MapIterator; import org.apache.commons.collections.OrderedMap; import org.apache.commons.collections.OrderedMapIterator; import org.apache.commons.collections.ResettableIterator; import org.apache.commons.collections.iterators.AbstractIteratorDecorator; import org.apache.commons.collections.keyvalue.AbstractMapEntry; import org.apache.commons.collections.list.UnmodifiableList; /** * 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. *

* Note that ListOrderedMap is not synchronized and is not thread-safe. * If you wish to use this map from multiple threads concurrently, you must use * appropriate synchronization. The simplest approach is to wrap this map * using {@link java.util.Collections#synchronizedMap(Map)}. This class may throw * exceptions when accessed by concurrent threads without synchronization. *

* This class is Serializable from Commons Collections 3.1. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Henri Yandell * @author Stephen Colebourne * @author Matt Benson */ 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 Object 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 Object 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 Object nextKey(Object 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 Object previousKey(Object key) { int index = insertOrder.indexOf(key); if (index > 0) { return insertOrder.get(index - 1); } return null; } //----------------------------------------------------------------------- public Object put(Object key, Object 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 Object 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(entry.getKey(), entry.getValue()); } } public Object remove(Object key) { Object result = getMap().remove(key); insertOrder.remove(key); return result; } public void clear() { getMap().clear(); insertOrder.clear(); } //----------------------------------------------------------------------- /** * Gets a view over the keys in the map. *

* The Collection will be ordered by object insertion into the map. * * @see #keyList() * @return the fully modifiable collection view over the keys */ public Set keySet() { return new KeySetView(this); } /** * Gets a view over the keys in the map as a List. *

* The List will be ordered by object insertion into the map. * The List is unmodifiable. * * @see #keySet() * @return the unmodifiable list view over the keys * @since Commons Collections 3.2 */ public List keyList() { return UnmodifiableList.decorate(insertOrder); } /** * Gets a view over the values in the map. *

* The Collection will be ordered by object insertion into the map. *

* From Commons Collections 3.2, this Collection can be cast * to a list, see {@link #valueList()} * * @see #valueList() * @return the fully modifiable collection view over the values */ public Collection values() { return new ValuesView(this); } /** * Gets a view over the values in the map as a List. *

* The List will be ordered by object insertion into the map. * The List supports remove and set, but does not support add. * * @see #values() * @return the partially modifiable list view over the values * @since Commons Collections 3.2 */ public List valueList() { return new ValuesView(this); } /** * Gets a view over the entries in the map. *

* The Set will be ordered by object insertion into the map. * * @return the fully modifiable set view over the entries */ 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 Object 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 Object 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); } /** * Sets the value at the specified index. * * @param index the index of the value to set * @return the previous value at that index * @throws IndexOutOfBoundsException if the index is invalid * @since Commons Collections 3.2 */ public Object setValue(int index, Object value) { Object key = insertOrder.get(index); return put(key, value); } /** * Puts a key-value mapping into the map at the specified index. *

* If the map already contains the key, then the original mapping * is removed and the new mapping added at the specified index. * The remove may change the effect of the index. The index is * always calculated relative to the original state of the map. *

* Thus the steps are: (1) remove the existing key-value mapping, * then (2) insert the new key-value mapping at the position it * would have been inserted had the remove not ocurred. * * @param index the index at which the mapping should be inserted * @param key the key * @param value the value * @return the value previously mapped to the key * @throws IndexOutOfBoundsException if the index is out of range * @since Commons Collections 3.2 */ public Object put(int index, Object key, Object value) { Map m = getMap(); if (m.containsKey(key)) { Object result = m.remove(key); int pos = insertOrder.indexOf(key); insertOrder.remove(pos); if (pos < index) { index--; } insertOrder.add(index, key); m.put(key, value); return result; } else { insertOrder.add(index, key); m.put(key, value); return null; } } /** * Removes the element at the specified index. * * @param index the index of the object to remove * @return the removed value, 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 the better named * {@link #keyList()} or {@link #keySet()}. * * @see #keyList() * @see #keySet() * @return The ordered list of keys. */ public List asList() { return keyList(); } //----------------------------------------------------------------------- static class ValuesView extends AbstractList { 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(); } }; } public Object get(int index) { return this.parent.getValue(index); } public Object set(int index, Object value) { return this.parent.setValue(index, value); } public Object remove(int index) { return this.parent.remove(index); } } //----------------------------------------------------------------------- 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() { return new AbstractIteratorDecorator(parent.entrySet().iterator()) { public Object next() { return ((Map.Entry) super.next()).getKey(); } }; } } //----------------------------------------------------------------------- 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 extends AbstractIteratorDecorator { private final ListOrderedMap parent; private Object last = null; ListOrderedIterator(ListOrderedMap parent, List insertOrder) { super(insertOrder.iterator()); this.parent = parent; } public Object next() { last = super.next(); return new ListOrderedMapEntry(parent, last); } public void remove() { super.remove(); parent.getMap().remove(last); } } //----------------------------------------------------------------------- static class ListOrderedMapEntry extends AbstractMapEntry { private final ListOrderedMap parent; ListOrderedMapEntry(ListOrderedMap parent, Object key) { super(key, null); this.parent = parent; } public Object getValue() { return parent.get(key); } public Object setValue(Object value) { return parent.getMap().put(key, value); } } //----------------------------------------------------------------------- static class ListOrderedMapIterator implements OrderedMapIterator, ResettableIterator { private final ListOrderedMap parent; private ListIterator iterator; private Object 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 Object next() { last = iterator.next(); readable = true; return last; } public boolean hasPrevious() { return iterator.hasPrevious(); } public Object 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 Object getKey() { if (readable == false) { throw new IllegalStateException(AbstractHashedMap.GETKEY_INVALID); } return last; } public Object getValue() { if (readable == false) { throw new IllegalStateException(AbstractHashedMap.GETVALUE_INVALID); } return parent.get(last); } public Object setValue(Object 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[]"; } } } } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/map/LRUMap.java0000644000175000017500000004151110777673462030057 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.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.collections.BoundedMap; /** * 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(). *

* Note that LRUMap is not synchronized and is not thread-safe. * If you wish to use this map from multiple threads concurrently, you must use * appropriate synchronization. The simplest approach is to wrap this map * using {@link java.util.Collections#synchronizedMap(Map)}. This class may throw * NullPointerException's when accessed by concurrent threads. * * @since Commons Collections 3.0 (previously in main package v1.0) * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author James Strachan * @author Morgan Delagrange * @author Stephen Colebourne * @author Mike Pettypiece * @author Mario Ivankovits */ public class LRUMap extends AbstractLinkedMap implements BoundedMap, Serializable, Cloneable { /** Serialisation version */ private 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 Object 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; } else if (entry == header) { throw new IllegalStateException("Can't move header to MRU" + " (please report this to commons-dev@jakarta.apache.org)"); } } /** * Updates an existing key-value mapping. *

* This implementation moves the updated entry to the top of the list * using {@link #moveToMRU(AbstractLinkedMap.LinkEntry)}. * * @param entry the entry to update * @param newValue the new value to store */ protected void updateEntry(HashEntry entry, Object 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(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, Object key, Object value) { if (isFull()) { LinkEntry reuse = header.after; boolean removeLRUEntry = false; if (scanUntilRemovable) { while (reuse != header && reuse != null) { if (removeLRU(reuse)) { removeLRUEntry = true; break; } reuse = reuse.after; } if (reuse == null) { throw new IllegalStateException( "Entry.after=null, header.after" + header.after + " header.before" + header.before + " key=" + key + " value=" + value + " size=" + size + " maxSize=" + maxSize + " Please check that your keys are immutable, and that you have used synchronization properly." + " If so, then please report this to commons-dev@jakarta.apache.org as a bug."); } } else { removeLRUEntry = removeLRU(reuse); } if (removeLRUEntry) { if (reuse == null) { throw new IllegalStateException( "reuse=null, header.after=" + header.after + " header.before" + header.before + " key=" + key + " value=" + value + " size=" + size + " maxSize=" + maxSize + " Please check that your keys are immutable, and that you have used synchronization properly." + " If so, then please report this to commons-dev@jakarta.apache.org as a bug."); } 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, Object key, Object 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 try { int removeIndex = hashIndex(entry.hashCode, data.length); HashEntry[] tmp = data; // may protect against some sync issues HashEntry loop = tmp[removeIndex]; HashEntry previous = null; while (loop != entry && loop != null) { previous = loop; loop = loop.next; } if (loop == null) { throw new IllegalStateException( "Entry.next=null, data[removeIndex]=" + data[removeIndex] + " previous=" + previous + " key=" + key + " value=" + value + " size=" + size + " maxSize=" + maxSize + " Please check that your keys are immutable, and that you have used synchronization properly." + " If so, then please report this to commons-dev@jakarta.apache.org as a bug."); } // reuse the entry modCount++; removeEntry(entry, removeIndex, previous); reuseEntry(entry, hashIndex, hashCode, key, value); addEntry(entry, hashIndex); } catch (NullPointerException ex) { throw new IllegalStateException( "NPE, entry=" + entry + " entryIsHeader=" + (entry==header) + " key=" + key + " value=" + value + " size=" + size + " maxSize=" + maxSize + " Please check that your keys are immutable, and that you have used synchronization properly." + " If so, then please report this to commons-dev@jakarta.apache.org as a bug."); } } /** * 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); } } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/map/MultiKeyMap.java0000644000175000017500000010014310777673462031155 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.map; import java.io.Serializable; import java.util.Collection; import java.util.Iterator; import java.util.Map; import java.util.Set; import org.apache.commons.collections.IterableMap; import org.apache.commons.collections.MapIterator; import org.apache.commons.collections.keyvalue.MultiKey; /** * 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;
 * }
 * 
*

* Note that MultiKeyMap is not synchronized and is not thread-safe. * If you wish to use this map from multiple threads concurrently, you must use * appropriate synchronization. This class may throw exceptions when accessed * by concurrent threads without synchronization. * * @since Commons Collections 3.1 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ public class MultiKeyMap implements IterableMap, Serializable { /** Serialisation version */ private static final long serialVersionUID = -1788199231038721040L; /** The decorated map */ protected final AbstractHashedMap 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 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(); } /** * 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 map) { super(); this.map = map; } //----------------------------------------------------------------------- /** * Gets the value mapped to the specified multi-key. * * @param key1 the first key * @param key2 the second key * @return the mapped value, null if no match */ public Object get(Object key1, Object key2) { int hashCode = hash(key1, key2); AbstractHashedMap.HashEntry entry = map.data[map.hashIndex(hashCode, map.data.length)]; while (entry != null) { if (entry.hashCode == hashCode && isEqualKey(entry, key1, key2)) { return entry.getValue(); } entry = entry.next; } return null; } /** * Checks whether the map contains the specified multi-key. * * @param key1 the first key * @param key2 the second key * @return true if the map contains the key */ public boolean containsKey(Object key1, Object key2) { int hashCode = hash(key1, key2); AbstractHashedMap.HashEntry entry = map.data[map.hashIndex(hashCode, map.data.length)]; while (entry != null) { if (entry.hashCode == hashCode && isEqualKey(entry, key1, key2)) { return true; } entry = entry.next; } return false; } /** * Stores the value against the specified multi-key. * * @param key1 the first key * @param key2 the second key * @param value the value to store * @return the value previously mapped to this combined key, null if none */ public Object put(Object key1, Object key2, Object value) { int hashCode = hash(key1, key2); int index = map.hashIndex(hashCode, map.data.length); AbstractHashedMap.HashEntry entry = map.data[index]; while (entry != null) { if (entry.hashCode == hashCode && isEqualKey(entry, key1, key2)) { Object oldValue = entry.getValue(); map.updateEntry(entry, value); return oldValue; } entry = entry.next; } map.addMapping(index, hashCode, new MultiKey(key1, key2), value); return null; } /** * Removes the specified multi-key from this map. * * @param key1 the first key * @param key2 the second key * @return the value mapped to the removed key, null if key not in map */ public Object remove(Object key1, Object key2) { int hashCode = hash(key1, key2); int index = map.hashIndex(hashCode, map.data.length); AbstractHashedMap.HashEntry entry = map.data[index]; AbstractHashedMap.HashEntry previous = null; while (entry != null) { if (entry.hashCode == hashCode && isEqualKey(entry, key1, key2)) { 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 key1 the first key * @param key2 the second key * @return the hash code */ 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; } /** * Is the key equal to the combined key. * * @param entry the entry to compare to * @param key1 the first key * @param key2 the second key * @return true if the key matches */ protected boolean isEqualKey(AbstractHashedMap.HashEntry entry, Object key1, Object key2) { MultiKey multi = (MultiKey) entry.getKey(); return 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))); } //----------------------------------------------------------------------- /** * Gets the value mapped to the specified multi-key. * * @param key1 the first key * @param key2 the second key * @param key3 the third key * @return the mapped value, null if no match */ public Object get(Object key1, Object key2, Object key3) { int hashCode = hash(key1, key2, key3); AbstractHashedMap.HashEntry entry = map.data[map.hashIndex(hashCode, map.data.length)]; while (entry != null) { if (entry.hashCode == hashCode && isEqualKey(entry, key1, key2, key3)) { return entry.getValue(); } entry = entry.next; } return null; } /** * Checks whether the map contains the specified multi-key. * * @param key1 the first key * @param key2 the second key * @param key3 the third key * @return true if the map contains the key */ public boolean containsKey(Object key1, Object key2, Object key3) { int hashCode = hash(key1, key2, key3); AbstractHashedMap.HashEntry entry = map.data[map.hashIndex(hashCode, map.data.length)]; while (entry != null) { if (entry.hashCode == hashCode && isEqualKey(entry, key1, key2, key3)) { return true; } entry = entry.next; } return false; } /** * Stores the value against the specified multi-key. * * @param key1 the first key * @param key2 the second key * @param key3 the third key * @param value the value to store * @return the value previously mapped to this combined key, null if none */ public Object put(Object key1, Object key2, Object key3, Object value) { int hashCode = hash(key1, key2, key3); int index = map.hashIndex(hashCode, map.data.length); AbstractHashedMap.HashEntry entry = map.data[index]; while (entry != null) { if (entry.hashCode == hashCode && isEqualKey(entry, key1, key2, key3)) { Object oldValue = entry.getValue(); map.updateEntry(entry, value); return oldValue; } entry = entry.next; } map.addMapping(index, hashCode, new MultiKey(key1, key2, key3), value); return null; } /** * Removes the specified multi-key from this map. * * @param key1 the first key * @param key2 the second key * @param key3 the third key * @return the value mapped to the removed key, null if key not in map */ public Object remove(Object key1, Object key2, Object key3) { int hashCode = hash(key1, key2, key3); int index = map.hashIndex(hashCode, map.data.length); AbstractHashedMap.HashEntry entry = map.data[index]; AbstractHashedMap.HashEntry previous = null; while (entry != null) { if (entry.hashCode == hashCode && isEqualKey(entry, key1, key2, key3)) { 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 key1 the first key * @param key2 the second key * @param key3 the third key * @return the hash code */ protected int hash(Object key1, Object key2, Object key3) { int h = 0; if (key1 != null) { h ^= key1.hashCode(); } if (key2 != null) { h ^= key2.hashCode(); } if (key3 != null) { h ^= key3.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 key1 the first key * @param key2 the second key * @param key3 the third key * @return true if the key matches */ protected boolean isEqualKey(AbstractHashedMap.HashEntry entry, Object key1, Object key2, Object key3) { MultiKey multi = (MultiKey) entry.getKey(); return 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))); } //----------------------------------------------------------------------- /** * Gets the value mapped to the specified multi-key. * * @param key1 the first key * @param key2 the second key * @param key3 the third key * @param key4 the fourth key * @return the mapped value, null if no match */ public Object get(Object key1, Object key2, Object key3, Object key4) { int hashCode = hash(key1, key2, key3, key4); AbstractHashedMap.HashEntry entry = map.data[map.hashIndex(hashCode, map.data.length)]; while (entry != null) { if (entry.hashCode == hashCode && isEqualKey(entry, key1, key2, key3, key4)) { return entry.getValue(); } entry = entry.next; } return null; } /** * Checks whether the map contains the specified multi-key. * * @param key1 the first key * @param key2 the second key * @param key3 the third key * @param key4 the fourth key * @return true if the map contains the key */ public boolean containsKey(Object key1, Object key2, Object key3, Object key4) { int hashCode = hash(key1, key2, key3, key4); AbstractHashedMap.HashEntry entry = map.data[map.hashIndex(hashCode, map.data.length)]; while (entry != null) { if (entry.hashCode == hashCode && isEqualKey(entry, key1, key2, key3, key4)) { return true; } entry = entry.next; } return false; } /** * Stores the value against the specified multi-key. * * @param key1 the first key * @param key2 the second key * @param key3 the third key * @param key4 the fourth key * @param value the value to store * @return the value previously mapped to this combined key, null if none */ public Object put(Object key1, Object key2, Object key3, Object key4, Object value) { int hashCode = hash(key1, key2, key3, key4); int index = map.hashIndex(hashCode, map.data.length); AbstractHashedMap.HashEntry entry = map.data[index]; while (entry != null) { if (entry.hashCode == hashCode && isEqualKey(entry, key1, key2, key3, key4)) { Object oldValue = entry.getValue(); map.updateEntry(entry, value); return oldValue; } entry = entry.next; } map.addMapping(index, hashCode, new MultiKey(key1, key2, key3, key4), value); return null; } /** * Removes the specified multi-key from this map. * * @param key1 the first key * @param key2 the second key * @param key3 the third key * @param key4 the fourth key * @return the value mapped to the removed key, null if key not in map */ public Object remove(Object key1, Object key2, Object key3, Object key4) { int hashCode = hash(key1, key2, key3, key4); int index = map.hashIndex(hashCode, map.data.length); AbstractHashedMap.HashEntry entry = map.data[index]; AbstractHashedMap.HashEntry previous = null; while (entry != null) { if (entry.hashCode == hashCode && isEqualKey(entry, key1, key2, key3, key4)) { 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 key1 the first key * @param key2 the second key * @param key3 the third key * @param key4 the fourth key * @return the hash code */ protected int hash(Object key1, Object key2, Object key3, Object key4) { int h = 0; if (key1 != null) { h ^= key1.hashCode(); } if (key2 != null) { h ^= key2.hashCode(); } if (key3 != null) { h ^= key3.hashCode(); } if (key4 != null) { h ^= key4.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 key1 the first key * @param key2 the second key * @param key3 the third key * @param key4 the fourth key * @return true if the key matches */ protected boolean isEqualKey(AbstractHashedMap.HashEntry entry, Object key1, Object key2, Object key3, Object key4) { MultiKey multi = (MultiKey) entry.getKey(); return 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))); } //----------------------------------------------------------------------- /** * Gets the value mapped to the specified multi-key. * * @param key1 the first key * @param key2 the second key * @param key3 the third key * @param key4 the fourth key * @param key5 the fifth key * @return the mapped value, null if no match */ public Object get(Object key1, Object key2, Object key3, Object key4, Object key5) { int hashCode = hash(key1, key2, key3, key4, key5); AbstractHashedMap.HashEntry entry = map.data[map.hashIndex(hashCode, map.data.length)]; while (entry != null) { if (entry.hashCode == hashCode && isEqualKey(entry, key1, key2, key3, key4, key5)) { return entry.getValue(); } entry = entry.next; } return null; } /** * Checks whether the map contains the specified multi-key. * * @param key1 the first key * @param key2 the second key * @param key3 the third key * @param key4 the fourth key * @param key5 the fifth key * @return true if the map contains the key */ public boolean containsKey(Object key1, Object key2, Object key3, Object key4, Object key5) { int hashCode = hash(key1, key2, key3, key4, key5); AbstractHashedMap.HashEntry entry = map.data[map.hashIndex(hashCode, map.data.length)]; while (entry != null) { if (entry.hashCode == hashCode && isEqualKey(entry, key1, key2, key3, key4, key5)) { return true; } entry = entry.next; } return false; } /** * Stores the value against the specified multi-key. * * @param key1 the first key * @param key2 the second key * @param key3 the third key * @param key4 the fourth key * @param key5 the fifth key * @param value the value to store * @return the value previously mapped to this combined key, null if none */ public Object put(Object key1, Object key2, Object key3, Object key4, Object key5, Object value) { int hashCode = hash(key1, key2, key3, key4, key5); int index = map.hashIndex(hashCode, map.data.length); AbstractHashedMap.HashEntry entry = map.data[index]; while (entry != null) { if (entry.hashCode == hashCode && isEqualKey(entry, key1, key2, key3, key4, key5)) { Object oldValue = entry.getValue(); map.updateEntry(entry, value); return oldValue; } entry = entry.next; } map.addMapping(index, hashCode, new MultiKey(key1, key2, key3, key4, key5), value); return null; } /** * Removes the specified multi-key from this map. * * @param key1 the first key * @param key2 the second key * @param key3 the third key * @param key4 the fourth key * @param key5 the fifth key * @return the value mapped to the removed key, null if key not in map */ public Object remove(Object key1, Object key2, Object key3, Object key4, Object key5) { int hashCode = hash(key1, key2, key3, key4, key5); int index = map.hashIndex(hashCode, map.data.length); AbstractHashedMap.HashEntry entry = map.data[index]; AbstractHashedMap.HashEntry previous = null; while (entry != null) { if (entry.hashCode == hashCode && isEqualKey(entry, key1, key2, key3, key4, key5)) { 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 key1 the first key * @param key2 the second key * @param key3 the third key * @param key4 the fourth key * @param key5 the fifth key * @return the hash code */ protected int hash(Object key1, Object key2, Object key3, Object key4, Object key5) { int h = 0; if (key1 != null) { h ^= key1.hashCode(); } if (key2 != null) { h ^= key2.hashCode(); } if (key3 != null) { h ^= key3.hashCode(); } if (key4 != null) { h ^= key4.hashCode(); } if (key5 != null) { h ^= key5.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 key1 the first key * @param key2 the second key * @param key3 the third key * @param key4 the fourth key * @param key5 the fifth key * @return true if the key matches */ protected boolean isEqualKey(AbstractHashedMap.HashEntry entry, Object key1, Object key2, Object key3, Object key4, Object key5) { MultiKey multi = (MultiKey) entry.getKey(); return multi.size() == 5 && (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))) && (key5 == null ? multi.getKey(4) == null : key5.equals(multi.getKey(4))); } //----------------------------------------------------------------------- /** * 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"); } if (key instanceof MultiKey == false) { throw new ClassCastException("Key must be a MultiKey"); } } /** * 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 Object put(Object key, Object value) { checkKey(key); return map.put(key, value); } /** * Copies all of the keys and values from the specified map to this map. * Each key must be non-null and a MultiKey object. * * @param mapToCopy to this map * @throws NullPointerException if the mapToCopy or any key within is null * @throws ClassCastException if any key in mapToCopy is not a MultiKey */ public void putAll(Map 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 Object get(Object key) { return map.get(key); } public Object 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(); } } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/map/MultiValueMap.java0000644000175000017500000003611510777673462031510 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.map; import java.util.AbstractCollection; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; import org.apache.commons.collections.Factory; import org.apache.commons.collections.FunctorException; import org.apache.commons.collections.MultiMap; import org.apache.commons.collections.iterators.EmptyIterator; import org.apache.commons.collections.iterators.IteratorChain; /** * A MultiValueMap decorates another map, allowing it to have * more than one value for a 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. *

* This implementation is a decorator, allowing any Map implementation * to be used as the base. *

* In addition, this implementation allows the type of collection used * for the values to be controlled. By default, an ArrayList * is used, however a Class to instantiate may be specified, * or a factory that returns a Collection instance. *

* Note that MultiValueMap is not synchronized and is not thread-safe. * If you wish to use this map from multiple threads concurrently, you must use * appropriate synchronization. This class may throw exceptions when accessed * by concurrent threads without synchronization. * * @author James Carman * @author Christopher Berry * @author James Strachan * @author Steve Downey * @author Stephen Colebourne * @author Julien Buret * @author Serhiy Yevtushenko * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * @since Commons Collections 3.2 */ public class MultiValueMap extends AbstractMapDecorator implements MultiMap { /** The factory for creating value collections. */ private final Factory collectionFactory; /** The cached values. */ private transient Collection values; /** * Creates a map which wraps the given map and * maps keys to ArrayLists. * * @param map the map to wrap */ public static MultiValueMap decorate(Map map) { return new MultiValueMap(map, new ReflectionFactory(ArrayList.class)); } /** * Creates a map which decorates the given map and * maps keys to collections of type collectionClass. * * @param map the map to wrap * @param collectionClass the type of the collection class */ public static MultiValueMap decorate(Map map, Class collectionClass) { return new MultiValueMap(map, new ReflectionFactory(collectionClass)); } /** * Creates a map which decorates the given map and * creates the value collections using the supplied collectionFactory. * * @param map the map to decorate * @param collectionFactory the collection factory (must return a Collection object). */ public static MultiValueMap decorate(Map map, Factory collectionFactory) { return new MultiValueMap(map, collectionFactory); } //----------------------------------------------------------------------- /** * Creates a MultiValueMap based on a HashMap and * storing the multiple values in an ArrayList. */ public MultiValueMap() { this(new HashMap(), new ReflectionFactory(ArrayList.class)); } /** * Creates a MultiValueMap which decorates the given map and * creates the value collections using the supplied collectionFactory. * * @param map the map to decorate * @param collectionFactory the collection factory which must return a Collection instance */ protected MultiValueMap(Map map, Factory collectionFactory) { super(map); if (collectionFactory == null) { throw new IllegalArgumentException("The factory must not be null"); } this.collectionFactory = collectionFactory; } //----------------------------------------------------------------------- /** * Clear the map. */ public void clear() { // If you believe that you have GC issues here, try uncommenting this code // Set pairs = getMap().entrySet(); // Iterator pairsIterator = pairs.iterator(); // while (pairsIterator.hasNext()) { // Map.Entry keyValuePair = (Map.Entry) pairsIterator.next(); // Collection coll = (Collection) keyValuePair.getValue(); // coll.clear(); // } getMap().clear(); } /** * 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 value the value to remove * @return the value removed (which was passed in), null if nothing removed */ public Object remove(Object key, Object value) { Collection valuesForKey = getCollection(key); if (valuesForKey == null) { return null; } boolean removed = valuesForKey.remove(value); if (removed == false) { return null; } if (valuesForKey.isEmpty()) { remove(key); } return value; } /** * Checks whether the map contains the value specified. *

* This checks all collections 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 = getMap().entrySet(); if (pairs == null) { return false; } Iterator pairsIterator = pairs.iterator(); while (pairsIterator.hasNext()) { Map.Entry keyValuePair = (Map.Entry) pairsIterator.next(); Collection coll = (Collection) keyValuePair.getValue(); if (coll.contains(value)) { return true; } } return false; } /** * 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 Object put(Object key, Object value) { boolean result = false; Collection coll = getCollection(key); if (coll == null) { coll = createCollection(1); result = coll.add(value); if (coll.size() > 0) { // only add if non-zero size to maintain class state getMap().put(key, coll); result = false; } } else { result = coll.add(value); } return (result ? value : null); } /** * Override superclass to ensure that MultiMap instances are * correctly handled. *

* If you call this method with a normal map, each entry is * added using put(Object,Object). * If you call this method with a multi map, each entry is * added using putAll(Object,Collection). * * @param map the map to copy (either a normal or multi map) */ public void putAll(Map map) { if (map instanceof MultiMap) { for (Iterator it = map.entrySet().iterator(); it.hasNext();) { Map.Entry entry = (Map.Entry) it.next(); Collection coll = (Collection) entry.getValue(); putAll(entry.getKey(), coll); } } else { for (Iterator it = map.entrySet().iterator(); it.hasNext();) { Map.Entry entry = (Map.Entry) it.next(); put(entry.getKey(), entry.getValue()); } } } /** * 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())); } /** * 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 */ public boolean containsValue(Object key, Object value) { Collection coll = getCollection(key); if (coll == null) { return false; } return coll.contains(value); } /** * 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 */ public Collection getCollection(Object key) { return (Collection) getMap().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 */ public int size(Object key) { Collection coll = getCollection(key); if (coll == null) { return 0; } return coll.size(); } /** * 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 */ public boolean putAll(Object key, Collection values) { if (values == null || values.size() == 0) { return false; } Collection coll = getCollection(key); if (coll == null) { coll = createCollection(values.size()); boolean result = coll.addAll(values); if (coll.size() > 0) { // only add if non-zero size to maintain class state getMap().put(key, coll); result = false; } return result; } else { return coll.addAll(values); } } /** * 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 */ public Iterator iterator(Object key) { if (!containsKey(key)) { return EmptyIterator.INSTANCE; } else { return new ValuesIterator(key); } } /** * Gets the total size of the map by counting all the values. * * @return the total size of the map counting all values */ public int totalSize() { int total = 0; Collection values = getMap().values(); for (Iterator it = values.iterator(); it.hasNext();) { Collection coll = (Collection) it.next(); total += coll.size(); } return total; } /** * Creates a new instance of the map value Collection container * using the factory. *

* This method can be overridden to perform your own processing * instead of using the factory. * * @param size the collection size that is about to be added * @return the new collection */ protected Collection createCollection(int size) { return (Collection) collectionFactory.create(); } //----------------------------------------------------------------------- /** * Inner class that provides the values view. */ private class Values extends AbstractCollection { public Iterator iterator() { final IteratorChain chain = new IteratorChain(); for (Iterator it = keySet().iterator(); it.hasNext();) { chain.addIterator(new ValuesIterator(it.next())); } return chain; } public int size() { return totalSize(); } public void clear() { MultiValueMap.this.clear(); } } /** * Inner class that provides the values iterator. */ private class ValuesIterator implements Iterator { private final Object key; private final Collection values; private final Iterator iterator; public ValuesIterator(Object key) { this.key = key; this.values = getCollection(key); this.iterator = values.iterator(); } public void remove() { iterator.remove(); if (values.isEmpty()) { MultiValueMap.this.remove(key); } } public boolean hasNext() { return iterator.hasNext(); } public Object next() { return iterator.next(); } } /** * Inner class that provides a simple reflection factory. */ private static class ReflectionFactory implements Factory { private final Class clazz; public ReflectionFactory(Class clazz) { this.clazz = clazz; } public Object create() { try { return clazz.newInstance(); } catch (Exception ex) { throw new FunctorException("Cannot instantiate class: " + clazz, ex); } } } } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/map/package.html0000644000175000017500000000544210777673462030400 0ustar godgod

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
libcommons-collections3-java.orig/src/java/org/apache/commons/collections/map/PredicatedMap.java0000644000175000017500000001572110777673462031465 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.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 org.apache.commons.collections.Predicate; /** * 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);
*

* Note that PredicatedMap is not synchronized and is not thread-safe. * If you wish to use this map from multiple threads concurrently, you must use * appropriate synchronization. The simplest approach is to wrap this map * using {@link java.util.Collections#synchronizedMap(Map)}. This class may throw * exceptions when accessed by concurrent threads without synchronization. *

* This class is Serializable from Commons Collections 3.1. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne * @author Paul Jack */ 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 = (Map.Entry) it.next(); Object key = entry.getKey(); Object 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(Object key, Object 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 Object checkSetValue(Object 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 Object put(Object key, Object 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(); Object key = entry.getKey(); Object value = entry.getValue(); validate(key, value); } map.putAll(mapToCopy); } } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/map/PredicatedSortedMap.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/map/PredicatedSortedMap.ja0000644000175000017500000001140610777673463032314 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.map; import java.util.Comparator; import java.util.SortedMap; import org.apache.commons.collections.Predicate; /** * 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);
*

* Note that PredicatedSortedMap is not synchronized and is not thread-safe. * If you wish to use this map from multiple threads concurrently, you must use * appropriate synchronization. The simplest approach is to wrap this map * using {@link java.util.Collections#synchronizedSortedMap}. This class may throw * exceptions when accessed by concurrent threads without synchronization. *

* This class is Serializable from Commons Collections 3.1. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne * @author Paul Jack */ 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 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 PredicatedSortedMap(map, keyPredicate, valuePredicate); } public SortedMap headMap(Object toKey) { SortedMap map = getSortedMap().headMap(toKey); return new PredicatedSortedMap(map, keyPredicate, valuePredicate); } public SortedMap tailMap(Object fromKey) { SortedMap map = getSortedMap().tailMap(fromKey); return new PredicatedSortedMap(map, keyPredicate, valuePredicate); } } ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/map/ReferenceIdentityMap.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/map/ReferenceIdentityMap.j0000644000175000017500000002175610777673462032346 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.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.collections.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 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(). *

* Note that ReferenceIdentityMap is not synchronized and is not thread-safe. * If you wish to use this map from multiple threads concurrently, you must use * appropriate synchronization. The simplest approach is to wrap this map * using {@link java.util.Collections#synchronizedMap}. This class may throw * exceptions when accessed by concurrent threads without synchronization. * * @see java.lang.ref.Reference * * @since Commons Collections 3.0 (previously in main package v2.1) * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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) { 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); } } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/map/ReferenceMap.java0000644000175000017500000001654110777673462031320 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.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 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.collections.map.ReferenceIdentityMap ReferenceIdentityMap}. * It differs in that keys and values in this class are compared using equals(). *

* This {@link java.util.Map 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 that ReferenceMap is not synchronized and is not thread-safe. * If you wish to use this map from multiple threads concurrently, you must use * appropriate synchronization. The simplest approach is to wrap this map * using {@link java.util.Collections#synchronizedMap}. This class may throw * exceptions when accessed by concurrent threads without synchronization. *

* 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. * * @see java.lang.ref.Reference * * @since Commons Collections 3.0 (previously in main package v2.1) * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Paul Jack * @author Stephen Colebourne */ 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); } } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/map/SingletonMap.java0000644000175000017500000004267510777673462031373 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.map; import java.io.Serializable; import java.util.AbstractSet; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; import org.apache.commons.collections.BoundedMap; import org.apache.commons.collections.KeyValue; import org.apache.commons.collections.MapIterator; import org.apache.commons.collections.OrderedMap; import org.apache.commons.collections.OrderedMapIterator; import org.apache.commons.collections.ResettableIterator; import org.apache.commons.collections.iterators.SingletonIterator; import org.apache.commons.collections.keyvalue.TiedMapEntry; /** * 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) *
* * @since Commons Collections 3.1 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ public class SingletonMap implements OrderedMap, BoundedMap, KeyValue, Serializable, Cloneable { /** Serialization version */ private static final long serialVersionUID = -8931271118676803261L; /** Singleton key */ private final Object key; /** Singleton value */ private Object 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(Object key, Object 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 mapEntry the mapEntry to use */ public SingletonMap(Map.Entry mapEntry) { super(); this.key = mapEntry.getKey(); this.value = mapEntry.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.Entry) map.entrySet().iterator().next(); this.key = entry.getKey(); this.value = entry.getValue(); } // KeyValue //----------------------------------------------------------------------- /** * Gets the key. * * @return the key */ public Object getKey() { return key; } /** * Gets the value. * * @return the value */ public Object getValue() { return value; } /** * Sets the value. * * @param value the new value to set * @return the old value */ public Object setValue(Object value) { Object 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 Object 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 Object put(Object key, Object 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.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 Object 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 Object firstKey() { return getKey(); } /** * Gets the last (and only) key in the map. * * @return the key */ public Object lastKey() { return getKey(); } /** * Gets the next key after the key specified, always null. * * @param key the next key * @return null always */ public Object nextKey(Object key) { return null; } /** * Gets the previous key before the key specified, always null. * * @param key the next key * @return null always */ public Object previousKey(Object 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 Object 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 Object previous() { if (hasNext == true) { throw new NoSuchElementException(AbstractHashedMap.NO_PREVIOUS_ENTRY); } hasNext = true; return parent.getKey(); } public void remove() { throw new UnsupportedOperationException(); } public Object getKey() { if (canGetSet == false) { throw new IllegalStateException(AbstractHashedMap.GETKEY_INVALID); } return parent.getKey(); } public Object getValue() { if (canGetSet == false) { throw new IllegalStateException(AbstractHashedMap.GETVALUE_INVALID); } return parent.getValue(); } public Object setValue(Object 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() == this ? "(this Map)" : getKey())) .append('=') .append((getValue() == this ? "(this Map)" : getValue())) .append('}') .toString(); } } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/map/StaticBucketMap.java0000644000175000017500000005204310777673463032005 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.map; import java.util.AbstractCollection; import java.util.AbstractSet; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; import org.apache.commons.collections.KeyValue; /** * 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.

* * @since Commons Collections 3.0 (previously in main package v2.1) * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Berin Loritsch * @author Gerhard Froehlich * @author Michael A. Smith * @author Paul Jack * @author Leo Sutic * @author Janek Bogucki * @author Kazuya Ujihara */ 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 Object 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 == key || (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 Object put(final Object key, final Object 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))) { Object 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 Object 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()) { Object key = i.next(); put(key, 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 Object key; protected Object value; protected Node next; public Object getKey() { return key; } public Object 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 Object setValue(Object obj) { Object 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 implements Iterator { 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 = (Map.Entry)current.remove(current.size() - 1); return last; } public Object next() { return nextEntry(); } public void remove() { if (last == null) throw new IllegalStateException(); StaticBucketMap.this.remove(last.getKey()); last = null; } } private class ValueIterator extends EntryIterator { public Object next() { return nextEntry().getValue(); } } private class KeyIterator extends EntryIterator { public Object 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); } } } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/map/TransformedMap.java0000644000175000017500000002070010777673463031677 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.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 org.apache.commons.collections.Transformer; /** * 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. *

* Note that TransformedMap is not synchronized and is not thread-safe. * If you wish to use this map from multiple threads concurrently, you must use * appropriate synchronization. The simplest approach is to wrap this map * using {@link java.util.Collections#synchronizedMap(Map)}. This class may throw * exceptions when accessed by concurrent threads without synchronization. *

* This class is Serializable from Commons Collections 3.1. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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. * Constrast this with {@link #decorateTransform}. * * @param map the map to decorate, must not be null * @param keyTransformer the transformer to use for key conversion, null means no transformation * @param valueTransformer the transformer to use for value conversion, null means no transformation * @throws IllegalArgumentException if map is null */ public static Map decorate(Map map, Transformer keyTransformer, Transformer valueTransformer) { return new TransformedMap(map, keyTransformer, valueTransformer); } /** * Factory method to create a transforming map that will transform * existing contents of the specified map. *

* If there are any elements already in the map being decorated, they * will be transformed by this method. * Constrast this with {@link #decorate}. * * @param map the map to decorate, must not be null * @param keyTransformer the transformer to use for key conversion, null means no transformation * @param valueTransformer the transformer to use for value conversion, null means no transformation * @throws IllegalArgumentException if map is null * @since Commons Collections 3.2 */ public static Map decorateTransform(Map map, Transformer keyTransformer, Transformer valueTransformer) { TransformedMap decorated = new TransformedMap(map, keyTransformer, valueTransformer); if (map.size() > 0) { Map transformed = decorated.transformMap(map); decorated.clear(); decorated.getMap().putAll(transformed); // avoids double transformation } return decorated; } //----------------------------------------------------------------------- /** * 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) { if (map.isEmpty()) { return 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); } } ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/map/TransformedSortedMap.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/map/TransformedSortedMap.j0000644000175000017500000001405710777673462032377 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.map; import java.util.Comparator; import java.util.Map; import java.util.SortedMap; import org.apache.commons.collections.Transformer; /** * 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. *

* Note that TransformedSortedMap is not synchronized and is not thread-safe. * If you wish to use this map from multiple threads concurrently, you must use * appropriate synchronization. The simplest approach is to wrap this map * using {@link java.util.Collections#synchronizedSortedMap}. This class may throw * exceptions when accessed by concurrent threads without synchronization. *

* This class is Serializable from Commons Collections 3.1. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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. * Constrast this with {@link #decorateTransform}. * * @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); } /** * Factory method to create a transforming sorted map that will transform * existing contents of the specified map. *

* If there are any elements already in the map being decorated, they * will be transformed by this method. * Constrast this with {@link #decorate}. * * @param map the map to decorate, must not be null * @param keyTransformer the transformer to use for key conversion, null means no transformation * @param valueTransformer the transformer to use for value conversion, null means no transformation * @throws IllegalArgumentException if map is null * @since Commons Collections 3.2 */ public static SortedMap decorateTransform(SortedMap map, Transformer keyTransformer, Transformer valueTransformer) { TransformedSortedMap decorated = new TransformedSortedMap(map, keyTransformer, valueTransformer); if (map.size() > 0) { Map transformed = decorated.transformMap(map); decorated.clear(); decorated.getMap().putAll(transformed); // avoids double transformation } return decorated; } //----------------------------------------------------------------------- /** * 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); } } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/map/TypedMap.java0000644000175000017500000000550310777673462030503 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.map; import java.util.Map; import org.apache.commons.collections.functors.InstanceofPredicate; /** * 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. *

* Note that TypedMap is not synchronized and is not thread-safe. * If you wish to use this map from multiple threads concurrently, you must use * appropriate synchronization. The simplest approach is to wrap this map * using {@link java.util.Collections#synchronizedMap(Map)}. This class may throw * exceptions when accessed by concurrent threads without synchronization. *

* The returned implementation is Serializable from Commons Collections 3.1. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne * @author Matthew Hawthorne */ 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() { } } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/map/TypedSortedMap.java0000644000175000017500000000557310777673462031673 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.map; import java.util.SortedMap; import org.apache.commons.collections.functors.InstanceofPredicate; /** * 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. *

* Note that TypedSortedMap is not synchronized and is not thread-safe. * If you wish to use this map from multiple threads concurrently, you must use * appropriate synchronization. The simplest approach is to wrap this map * using {@link java.util.Collections#synchronizedSortedMap}. This class may throw * exceptions when accessed by concurrent threads without synchronization. *

* The returned implementation is Serializable from Commons Collections 3.1. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne * @author Matthew Hawthorne */ 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() { } } ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/map/UnmodifiableEntrySet.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/map/UnmodifiableEntrySet.j0000644000175000017500000001272110777673463032365 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.map; import java.lang.reflect.Array; import java.util.Collection; import java.util.Iterator; import java.util.Map; import java.util.Set; import org.apache.commons.collections.Unmodifiable; import org.apache.commons.collections.iterators.AbstractIteratorDecorator; import org.apache.commons.collections.keyvalue.AbstractMapEntryDecorator; import org.apache.commons.collections.set.AbstractSetDecorator; /** * Decorates a map entry Set to ensure it can't be altered. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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(Object 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 Object[] toArray(Object 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 = (Object[]) Array.newInstance(array.getClass().getComponentType(), 0); } result = collection.toArray(result); for (int i = 0; i < result.length; i++) { result[i] = new UnmodifiableEntry((Map.Entry) result[i]); } // 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 Object 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 Object setValue(Object obj) { throw new UnsupportedOperationException(); } } } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/map/UnmodifiableMap.java0000644000175000017500000001132410777673463032013 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.map; 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; import org.apache.commons.collections.IterableMap; import org.apache.commons.collections.MapIterator; import org.apache.commons.collections.Unmodifiable; import org.apache.commons.collections.collection.UnmodifiableCollection; import org.apache.commons.collections.iterators.EntrySetMapIterator; import org.apache.commons.collections.iterators.UnmodifiableMapIterator; import org.apache.commons.collections.set.UnmodifiableSet; /** * Decorates another Map to ensure it can't be altered. *

* This class is Serializable from Commons Collections 3.1. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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 Object put(Object key, Object value) { throw new UnsupportedOperationException(); } public void putAll(Map mapToCopy) { throw new UnsupportedOperationException(); } public Object 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); } } ././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/map/UnmodifiableOrderedMap.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/map/UnmodifiableOrderedMap0000644000175000017500000001150410777673462032377 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.map; 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; import org.apache.commons.collections.MapIterator; import org.apache.commons.collections.OrderedMap; import org.apache.commons.collections.OrderedMapIterator; import org.apache.commons.collections.Unmodifiable; import org.apache.commons.collections.collection.UnmodifiableCollection; import org.apache.commons.collections.iterators.UnmodifiableMapIterator; import org.apache.commons.collections.iterators.UnmodifiableOrderedMapIterator; import org.apache.commons.collections.set.UnmodifiableSet; /** * Decorates another OrderedMap to ensure it can't be altered. *

* This class is Serializable from Commons Collections 3.1. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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 Object put(Object key, Object value) { throw new UnsupportedOperationException(); } public void putAll(Map mapToCopy) { throw new UnsupportedOperationException(); } public Object 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); } } ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/map/UnmodifiableSortedMap.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/map/UnmodifiableSortedMap.0000644000175000017500000001204010777673462032325 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.map; 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.Map; import java.util.Set; import java.util.SortedMap; import org.apache.commons.collections.Unmodifiable; import org.apache.commons.collections.collection.UnmodifiableCollection; import org.apache.commons.collections.set.UnmodifiableSet; /** * Decorates another SortedMap to ensure it can't be altered. *

* This class is Serializable from Commons Collections 3.1. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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 Object put(Object key, Object value) { throw new UnsupportedOperationException(); } public void putAll(Map mapToCopy) { throw new UnsupportedOperationException(); } public Object 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 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 UnmodifiableSortedMap(map); } public SortedMap headMap(Object toKey) { SortedMap map = getSortedMap().headMap(toKey); return new UnmodifiableSortedMap(map); } public SortedMap tailMap(Object fromKey) { SortedMap map = getSortedMap().tailMap(fromKey); return new UnmodifiableSortedMap(map); } } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/set/0000755000175000017500000000000011010124151026067 5ustar godgod././@LongLink0000000000000000000000000000016400000000000011566 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/set/AbstractSerializableSetDecorator.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/set/AbstractSerializableSe0000644000175000017500000000440710777673465032445 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.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 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(); } } ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/set/AbstractSetDecorator.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/set/AbstractSetDecorator.j0000644000175000017500000000375610777673465032403 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.set; import java.util.Set; import org.apache.commons.collections.collection.AbstractCollectionDecorator; /** * Decorates another Set to provide additional behaviour. *

* Methods are forwarded directly to the decorated set. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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(); } } ././@LongLink0000000000000000000000000000015600000000000011567 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/set/AbstractSortedSetDecorator.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/set/AbstractSortedSetDecor0000644000175000017500000000527610777673465032445 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.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. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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(Object fromElement, Object toElement) { return getSortedSet().subSet(fromElement, toElement); } public SortedSet headSet(Object toElement) { return getSortedSet().headSet(toElement); } public SortedSet tailSet(Object fromElement) { return getSortedSet().tailSet(fromElement); } public Object first() { return getSortedSet().first(); } public Object last() { return getSortedSet().last(); } public Comparator comparator() { return getSortedSet().comparator(); } } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/set/CompositeSet.java0000644000175000017500000001656210777673465031426 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.set; import java.util.Collection; import java.util.Iterator; import java.util.Set; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.collection.CompositeCollection; /** * 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 operations require the use of a pluggable strategy. * If no strategy is provided then add is unsupported. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Brian McCallister */ 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.collections.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(new Collection[]{c}); } /** * Add two sets to this composite * * @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 collections 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); } } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/set/ListOrderedSet.java0000644000175000017500000002433010777673465031674 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.set; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import org.apache.commons.collections.iterators.AbstractIteratorDecorator; import org.apache.commons.collections.list.UnmodifiableList; /** * 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. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne * @author Henning P. Schmiedehausen */ 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. *

* The list and set must both be empty. * * @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. *

* NOTE: If the list contains duplicates, the duplicates are removed, * altering the specified list. * * @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(Object 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();) { Object 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 Object[] toArray(Object a[]) { return setOrder.toArray(a); } //----------------------------------------------------------------------- public Object get(int index) { return setOrder.get(index); } public int indexOf(Object object) { return setOrder.indexOf(object); } public void add(int index, Object 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();) { Object object = it.next(); if (contains(object) == false) { collection.add(object); setOrder.add(index, object); index++; changed = true; } } return changed; } public Object remove(int index) { Object 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 Object last; private OrderedSetIterator(Iterator iterator, Collection set) { super(iterator); this.set = set; } public Object next() { last = iterator.next(); return last; } public void remove() { set.remove(last); iterator.remove(); last = null; } } } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/set/MapBackedSet.java0000644000175000017500000001145710777673465031271 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.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. * * @since Commons Collections 3.1 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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 Object 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, Object 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, Object 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(Object 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();) { Object 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 Object[] toArray(Object[] array) { return map.keySet().toArray(array); } public boolean equals(Object obj) { return map.keySet().equals(obj); } public int hashCode() { return map.keySet().hashCode(); } } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/set/package.html0000644000175000017500000000357610777673465030427 0ustar godgod

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
libcommons-collections3-java.orig/src/java/org/apache/commons/collections/set/PredicatedSet.java0000644000175000017500000000650710777673465031526 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.set; import java.util.Set; import org.apache.commons.collections.Predicate; import org.apache.commons.collections.collection.PredicatedCollection; /** * 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. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne * @author Paul Jack */ 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(); } } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/set/PredicatedSortedSet.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/set/PredicatedSortedSet.ja0000644000175000017500000001036610777673465032356 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.set; import java.util.Comparator; import java.util.SortedSet; import org.apache.commons.collections.Predicate; /** * 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. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne * @author Paul Jack */ 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(Object fromElement, Object toElement) { SortedSet sub = getSortedSet().subSet(fromElement, toElement); return new PredicatedSortedSet(sub, predicate); } public SortedSet headSet(Object toElement) { SortedSet sub = getSortedSet().headSet(toElement); return new PredicatedSortedSet(sub, predicate); } public SortedSet tailSet(Object fromElement) { SortedSet sub = getSortedSet().tailSet(fromElement); return new PredicatedSortedSet(sub, predicate); } public Object first() { return getSortedSet().first(); } public Object last() { return getSortedSet().last(); } public Comparator comparator() { return getSortedSet().comparator(); } } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/set/SynchronizedSet.java0000644000175000017500000000524610777673465032140 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.set; import java.util.Set; import org.apache.commons.collections.collection.SynchronizedCollection; /** * 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. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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; } } ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/set/SynchronizedSortedSet.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/set/SynchronizedSortedSet.0000644000175000017500000001055210777673465032453 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.set; import java.util.Comparator; import java.util.SortedSet; import org.apache.commons.collections.collection.SynchronizedCollection; /** * 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. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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(Object fromElement, Object 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(Object 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(Object 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 Object first() { synchronized (lock) { return getSortedSet().first(); } } public Object last() { synchronized (lock) { return getSortedSet().last(); } } public Comparator comparator() { synchronized (lock) { return getSortedSet().comparator(); } } } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/set/TransformedSet.java0000644000175000017500000000555510777673465031750 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.set; import java.util.Set; import org.apache.commons.collections.Transformer; import org.apache.commons.collections.collection.TransformedCollection; /** * 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. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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); } } ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/set/TransformedSortedSet.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/set/TransformedSortedSet.j0000644000175000017500000001000210777673465032420 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.set; import java.util.Comparator; import java.util.SortedSet; import org.apache.commons.collections.Transformer; /** * 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. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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); } } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/set/TypedSet.java0000644000175000017500000000424310777673465030542 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.set; import java.util.Set; import org.apache.commons.collections.functors.InstanceofPredicate; /** * 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. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne * @author Matthew Hawthorne */ 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() { } } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/set/TypedSortedSet.java0000644000175000017500000000432410777673465031723 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.set; import java.util.SortedSet; import org.apache.commons.collections.functors.InstanceofPredicate; /** * 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. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne * @author Matthew Hawthorne */ 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() { } } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/set/UnmodifiableSet.java0000644000175000017500000000612210777673465032051 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.set; import java.util.Collection; import java.util.Iterator; import java.util.Set; import org.apache.commons.collections.Unmodifiable; import org.apache.commons.collections.iterators.UnmodifiableIterator; /** * Decorates another Set to ensure it can't be altered. *

* This class is Serializable from Commons Collections 3.1. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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(Object 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(); } } ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/set/UnmodifiableSortedSet.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/set/UnmodifiableSortedSet.0000644000175000017500000001115410777673465032371 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.set; 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; import org.apache.commons.collections.Unmodifiable; import org.apache.commons.collections.iterators.UnmodifiableIterator; /** * Decorates another SortedSet to ensure it can't be altered. *

* This class is Serializable from Commons Collections 3.1. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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(Object 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(Object fromElement, Object toElement) { SortedSet sub = getSortedSet().subSet(fromElement, toElement); return new UnmodifiableSortedSet(sub); } public SortedSet headSet(Object toElement) { SortedSet sub = getSortedSet().headSet(toElement); return new UnmodifiableSortedSet(sub); } public SortedSet tailSet(Object fromElement) { SortedSet sub = getSortedSet().tailSet(fromElement); return new UnmodifiableSortedSet(sub); } } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/ArrayStack.java0000644000175000017500000001465410777673521030252 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; 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. * * @see java.util.Stack * @since Commons Collections 1.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Craig R. McClanahan * @author Paul Jack * @author Stephen Colebourne */ 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 Object 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 Object 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 Object 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 Object push(Object 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(Object object) { int i = size() - 1; // Current index int n = 1; // Current distance while (i >= 0) { Object 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 Object 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 Object remove() { int size = size(); if (size == 0) { throw new BufferUnderflowException(); } return remove(size - 1); } } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/Bag.java0000644000175000017500000002170510777673522026673 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; 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. * * @since Commons Collections 2.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Chuck Burdick * @author Stephen Colebourne */ 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(Object 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(Object 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(Object 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(Object 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(); } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/BagUtils.java0000644000175000017500000002334510777673521027715 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; import org.apache.commons.collections.bag.HashBag; import org.apache.commons.collections.bag.PredicatedBag; import org.apache.commons.collections.bag.PredicatedSortedBag; import org.apache.commons.collections.bag.SynchronizedBag; import org.apache.commons.collections.bag.SynchronizedSortedBag; import org.apache.commons.collections.bag.TransformedBag; import org.apache.commons.collections.bag.TransformedSortedBag; import org.apache.commons.collections.bag.TreeBag; import org.apache.commons.collections.bag.TypedBag; import org.apache.commons.collections.bag.TypedSortedBag; import org.apache.commons.collections.bag.UnmodifiableBag; import org.apache.commons.collections.bag.UnmodifiableSortedBag; /** * Provides utility methods and decorators for * {@link Bag} and {@link SortedBag} instances. * * @since Commons Collections 2.1 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Paul Jack * @author Stephen Colebourne * @author Andrew Freeman * @author Matthew Hawthorne */ 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 */ 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 */ 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 */ 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 */ public static SortedBag transformedSortedBag(SortedBag bag, Transformer transformer) { return TransformedSortedBag.decorate(bag, transformer); } } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/BeanMap.java0000644000175000017500000007020610777673522027505 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; 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.AbstractMap; import java.util.AbstractSet; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.Set; import org.apache.commons.collections.list.UnmodifiableList; import org.apache.commons.collections.keyvalue.AbstractMapEntry; import org.apache.commons.collections.set.UnmodifiableSet; /** * 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 * * @since Commons Collections 1.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author James Strachan * @author Stephen Colebourne * @author Dimiter Dimitrov * * @deprecated Identical class now available in commons-beanutils (full jar version). * This version is due to be removed in collections v4.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()) { Object 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()) { Object 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(Object 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(Object 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(Object 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 Object next() { Object 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 (Method) 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 //------------------------------------------------------------------------- /** * Returns the accessor for the property with the given name. * * @param name the name of the property * @return null if the name is null; null if the name is not a * {@link String}; null if no such property exists; or the accessor * method for that property */ protected Method getReadMethod( Object name ) { return (Method) readMethods.get( name ); } /** * Returns the mutator for the property with the given name. * * @param name the name of the * @return null if the name is null; null if the name is not a * {@link String}; null if no such property exists; null if the * property is read-only; or the mutator method for that property */ protected Method getWriteMethod( Object name ) { return (Method) writeMethods.get( name ); } /** * 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 ( writeMethod != 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( Object 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, Object 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) { Object 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(); } } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/BidiMap.java0000644000175000017500000001416110777673522027505 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; /** * 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. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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 */ Object put(Object key, Object 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 */ Object 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 */ Object 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(); } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/BinaryHeap.java0000644000175000017500000004357610777673521030235 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; import java.util.AbstractCollection; import java.util.Comparator; import java.util.Iterator; import java.util.NoSuchElementException; /** * Binary heap implementation of PriorityQueue. *

      * The PriorityQueue interface has now been replaced for most uses * by the Buffer interface. This class and the interface are * retained for backwards compatibility. The intended replacement is * {@link org.apache.commons.collections.buffer.PriorityBuffer PriorityBuffer}. *

      * 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 #pop()} method always returns the first element as determined * by the sort order. (The isMinHeap flag in the constructors * can be used to reverse the sort order, in which case {@link #pop()} * 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 #insert(Object)} and {@link #pop()} operations perform * in logarithmic time. The {@link #peek()} operation performs in constant * time. All other operations perform in linear time or worse. *

      * Note that this implementation is not synchronized. Use SynchronizedPriorityQueue * to provide synchronized access to a BinaryHeap: * *

       * PriorityQueue heap = new SynchronizedPriorityQueue(new BinaryHeap());
       * 
      * * @deprecated Replaced by PriorityBuffer in buffer subpackage. * Due to be removed in v4.0. * @since Commons Collections 1.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Peter Donald * @author Ram Chidambaram * @author Michael A. Smith * @author Paul Jack * @author Stephen Colebourne */ public final class BinaryHeap extends AbstractCollection implements PriorityQueue, Buffer { /** * The default capacity for a binary heap. */ private final static int DEFAULT_CAPACITY = 13; /** * The number of elements currently in this heap. */ int m_size; // package scoped for testing /** * The elements in this heap. */ Object[] m_elements; // package scoped for testing /** * 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. */ boolean m_isMinHeap; // package scoped for testing /** * The comparator used to order the elements */ Comparator m_comparator; // package scoped for testing /** * Constructs a new minimum binary heap. */ public BinaryHeap() { this(DEFAULT_CAPACITY, true); } /** * Constructs a new BinaryHeap that will use the given * comparator to order its elements. * * @param comparator the comparator used to order the elements, null * means use natural order */ public BinaryHeap(Comparator comparator) { this(); m_comparator = comparator; } /** * Constructs a new minimum binary heap with the specified initial capacity. * * @param capacity The initial capacity for the heap. This value must * be greater than zero. * @throws IllegalArgumentException * if capacity is <= 0 */ public BinaryHeap(int capacity) { this(capacity, true); } /** * Constructs a new BinaryHeap. * * @param capacity the initial capacity for the heap * @param comparator the comparator used to order the elements, null * means use natural order * @throws IllegalArgumentException * if capacity is <= 0 */ public BinaryHeap(int capacity, Comparator comparator) { this(capacity); m_comparator = comparator; } /** * Constructs a new minimum or maximum binary heap * * @param isMinHeap if true the heap is created as a * minimum heap; otherwise, the heap is created as a maximum heap */ public BinaryHeap(boolean isMinHeap) { this(DEFAULT_CAPACITY, isMinHeap); } /** * Constructs a new BinaryHeap. * * @param isMinHeap 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 BinaryHeap(boolean isMinHeap, Comparator comparator) { this(isMinHeap); m_comparator = comparator; } /** * Constructs a new minimum or maximum binary heap with the specified * initial capacity. * * @param capacity the initial capacity for the heap. This value must * be greater than zero. * @param isMinHeap 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 BinaryHeap(int capacity, boolean isMinHeap) { if (capacity <= 0) { throw new IllegalArgumentException("invalid capacity"); } m_isMinHeap = isMinHeap; //+1 as 0 is noop m_elements = new Object[capacity + 1]; } /** * Constructs a new BinaryHeap. * * @param capacity the initial capacity for the heap * @param isMinHeap 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 BinaryHeap(int capacity, boolean isMinHeap, Comparator comparator) { this(capacity, isMinHeap); m_comparator = comparator; } //----------------------------------------------------------------------- /** * Clears all elements from queue. */ public void clear() { m_elements = new Object[m_elements.length]; // for gc m_size = 0; } /** * Tests if queue is empty. * * @return true if queue is empty; false * otherwise. */ public boolean isEmpty() { return m_size == 0; } /** * Tests if queue is full. * * @return true if queue is full; false * otherwise. */ public boolean isFull() { //+1 as element 0 is noop return m_elements.length == m_size + 1; } /** * Inserts an element into queue. * * @param element the element to be inserted */ public void insert(Object element) { if (isFull()) { grow(); } //percolate element to it's place in tree if (m_isMinHeap) { percolateUpMinHeap(element); } else { percolateUpMaxHeap(element); } } /** * Returns the element on top of heap but don't remove it. * * @return the element at top of heap * @throws NoSuchElementException if isEmpty() == true */ public Object peek() throws NoSuchElementException { if (isEmpty()) { throw new NoSuchElementException(); } else { return m_elements[1]; } } /** * Returns the element on top of heap and remove it. * * @return the element at top of heap * @throws NoSuchElementException if isEmpty() == true */ public Object pop() throws NoSuchElementException { final Object result = peek(); m_elements[1] = m_elements[m_size--]; // set the unused element to 'null' so that the garbage collector // can free the object if not used anywhere else.(remove reference) m_elements[m_size + 1] = null; if (m_size != 0) { // percolate top element to it's place in tree if (m_isMinHeap) { percolateDownMinHeap(1); } else { percolateDownMaxHeap(1); } } return result; } /** * 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 Object element = m_elements[index]; int hole = index; while ((hole * 2) <= m_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 != m_size && compare(m_elements[child + 1], m_elements[child]) < 0) { child++; } // if we found resting place of bubble then terminate search if (compare(m_elements[child], element) >= 0) { break; } m_elements[hole] = m_elements[child]; hole = child; } m_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 Object element = m_elements[index]; int hole = index; while ((hole * 2) <= m_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 != m_size && compare(m_elements[child + 1], m_elements[child]) > 0) { child++; } // if we found resting place of bubble then terminate search if (compare(m_elements[child], element) <= 0) { break; } m_elements[hole] = m_elements[child]; hole = child; } m_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; Object element = m_elements[hole]; while (hole > 1 && compare(element, m_elements[hole / 2]) < 0) { // save element that is being pushed down // as the element "bubble" is percolated up final int next = hole / 2; m_elements[hole] = m_elements[next]; hole = next; } m_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 Object element) { m_elements[++m_size] = element; percolateUpMinHeap(m_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; Object element = m_elements[hole]; while (hole > 1 && compare(element, m_elements[hole / 2]) > 0) { // save element that is being pushed down // as the element "bubble" is percolated up final int next = hole / 2; m_elements[hole] = m_elements[next]; hole = next; } m_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 Object element) { m_elements[++m_size] = element; percolateUpMaxHeap(m_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 */ private int compare(Object a, Object b) { if (m_comparator != null) { return m_comparator.compare(a, b); } else { return ((Comparable) a).compareTo(b); } } /** * Increases the size of the heap to support additional elements */ protected void grow() { final Object[] elements = new Object[m_elements.length * 2]; System.arraycopy(m_elements, 0, elements, 0, m_elements.length); m_elements = elements; } /** * Returns a string representation of this heap. The returned string * is similar to those produced by standard JDK collections. * * @return a string representation of this heap */ public String toString() { final StringBuffer sb = new StringBuffer(); sb.append("[ "); for (int i = 1; i < m_size + 1; i++) { if (i != 1) { sb.append(", "); } sb.append(m_elements[i]); } sb.append(" ]"); return sb.toString(); } /** * 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 <= m_size; } public Object next() { if (!hasNext()) throw new NoSuchElementException(); lastReturnedIndex = index; index++; return m_elements[lastReturnedIndex]; } public void remove() { if (lastReturnedIndex == -1) { throw new IllegalStateException(); } m_elements[ lastReturnedIndex ] = m_elements[ m_size ]; m_elements[ m_size ] = null; m_size--; if( m_size != 0 && lastReturnedIndex <= m_size) { int compareToParent = 0; if (lastReturnedIndex > 1) { compareToParent = compare(m_elements[lastReturnedIndex], m_elements[lastReturnedIndex / 2]); } if (m_isMinHeap) { 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; } }; } /** * Adds an object to this heap. Same as {@link #insert(Object)}. * * @param object the object to add * @return true, always */ public boolean add(Object object) { insert(object); return true; } /** * Returns the priority element. Same as {@link #peek()}. * * @return the priority element * @throws BufferUnderflowException if this heap is empty */ public Object get() { try { return peek(); } catch (NoSuchElementException e) { throw new BufferUnderflowException(); } } /** * Removes the priority element. Same as {@link #pop()}. * * @return the removed priority element * @throws BufferUnderflowException if this heap is empty */ public Object remove() { try { return pop(); } catch (NoSuchElementException e) { throw new BufferUnderflowException(); } } /** * Returns the number of elements in this heap. * * @return the number of elements in this heap */ public int size() { return m_size; } } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/BoundedCollection.java0000644000175000017500000000351510777673521031574 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; 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. * * @see CollectionUtils#isFull * @see CollectionUtils#maxSize * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Herve Quiroz * @author Stephen Colebourne */ 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(); } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/BoundedFifoBuffer.java0000644000175000017500000002222610777673522031517 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; import java.util.AbstractCollection; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.NoSuchElementException; /** * 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. * * @deprecated Moved to buffer subpackage. Due to be removed in v4.0. * @since 2.1 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Avalon * @author Berin Loritsch * @author Paul Jack * @author Stephen Colebourne * @author Herve Quiroz */ public class BoundedFifoBuffer extends AbstractCollection implements Buffer, BoundedCollection { private final Object[] m_elements; private int m_start = 0; private int m_end = 0; private boolean m_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"); } m_elements = new Object[size]; maxElements = m_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); } /** * Returns the number of elements stored in the buffer. * * @return this buffer's size */ public int size() { int size = 0; if (m_end < m_start) { size = maxElements - m_start + m_end; } else if (m_end == m_start) { size = (m_full ? maxElements : 0); } else { size = m_end - m_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() { m_full = false; m_start = 0; m_end = 0; Arrays.fill(m_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(Object element) { if (null == element) { throw new NullPointerException("Attempted to add null object to buffer"); } if (m_full) { throw new BufferOverflowException("The buffer cannot hold more than " + maxElements + " objects."); } m_elements[m_end++] = element; if (m_end >= maxElements) { m_end = 0; } if (m_end == m_start) { m_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 Object get() { if (isEmpty()) { throw new BufferUnderflowException("The buffer is already empty"); } return m_elements[m_start]; } /** * Removes the least recently inserted element from this buffer. * * @return the least recently inserted element * @throws BufferUnderflowException if the buffer is empty */ public Object remove() { if (isEmpty()) { throw new BufferUnderflowException("The buffer is already empty"); } Object element = m_elements[m_start]; if (null != element) { m_elements[m_start++] = null; if (m_start >= maxElements) { m_start = 0; } m_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 = m_start; private int lastReturnedIndex = -1; private boolean isFirst = m_full; public boolean hasNext() { return isFirst || (index != m_end); } public Object next() { if (!hasNext()) throw new NoSuchElementException(); isFirst = false; lastReturnedIndex = index; index = increment(index); return m_elements[lastReturnedIndex]; } public void remove() { if (lastReturnedIndex == -1) throw new IllegalStateException(); // First element can be removed quickly if (lastReturnedIndex == m_start) { BoundedFifoBuffer.this.remove(); lastReturnedIndex = -1; return; } // Other elements require us to shift the subsequent elements int i = lastReturnedIndex + 1; while (i != m_end) { if (i >= maxElements) { m_elements[i - 1] = m_elements[0]; i = 0; } else { m_elements[i - 1] = m_elements[i]; i++; } } lastReturnedIndex = -1; m_end = decrement(m_end); m_elements[m_end] = null; m_full = false; index = decrement(index); } }; } } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/BoundedMap.java0000644000175000017500000000326010777673522030214 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; 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. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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(); } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/Buffer.java0000644000175000017500000000473210777673522027414 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; 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}. * * @since Commons Collections 2.1 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Avalon * @author Berin Loritsch * @author Paul Jack * @author Stephen Colebourne */ 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 */ Object 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 */ Object get(); } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/BufferOverflowException.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/BufferOverflowException.ja0000644000175000017500000000455710777673522032475 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; /** * The BufferOverflowException is used when the buffer's capacity has been * exceeded. * * @since Commons Collections 2.1 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Avalon * @author Berin Loritsch * @author Jeff Turner * @author Paul Jack * @author Stephen Colebourne */ 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; } } ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/BufferUnderflowException.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/BufferUnderflowException.j0000644000175000017500000000463410777673521032471 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; import java.util.NoSuchElementException; /** * The BufferUnderflowException is used when the buffer is already empty. *

      * NOTE: From version 3.0, this exception extends NoSuchElementException. * * @since Commons Collections 2.1 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Avalon * @author Berin Loritsch * @author Jeff Turner * @author Paul Jack * @author Stephen Colebourne */ 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; } } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/BufferUtils.java0000644000175000017500000002111010777673522030422 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; import org.apache.commons.collections.buffer.BlockingBuffer; import org.apache.commons.collections.buffer.PredicatedBuffer; import org.apache.commons.collections.buffer.SynchronizedBuffer; import org.apache.commons.collections.buffer.TransformedBuffer; import org.apache.commons.collections.buffer.TypedBuffer; import org.apache.commons.collections.buffer.UnmodifiableBuffer; import org.apache.commons.collections.buffer.BoundedBuffer; /** * Provides utility methods and decorators for {@link Buffer} instances. * * @since Commons Collections 2.1 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Paul Jack * @author Stephen Colebourne */ 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 collections 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 a synchronized buffer backed by the given buffer that will * block on {@link Buffer#get()} and {@link Buffer#remove()} operations * until timeout expires. 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 * @param timeoutMillis the timeout value in milliseconds, zero or less for no timeout * @return a blocking buffer backed by that buffer * @throws IllegalArgumentException if the Buffer is null * @since Commons Collections 3.2 */ public static Buffer blockingBuffer(Buffer buffer, long timeoutMillis) { return BlockingBuffer.decorate(buffer, timeoutMillis); } /** * Returns a synchronized buffer backed by the given buffer that will * block on {@link Buffer#add(Object)} and * {@link Buffer#addAll(java.util.Collection)} until enough object(s) are * removed from the buffer to allow the object(s) to be added and still * maintain the maximum size. * * @param buffer the buffer to make bounded, must not be null * @param maximumSize the maximum size * @return a bounded buffer backed by the given buffer * @throws IllegalArgumentException if the given buffer is null * @since Commons Collections 3.2 */ public static Buffer boundedBuffer(Buffer buffer, int maximumSize) { return BoundedBuffer.decorate(buffer, maximumSize); } /** * Returns a synchronized buffer backed by the given buffer that will * block on {@link Buffer#add(Object)} and * {@link Buffer#addAll(java.util.Collection)} until enough object(s) are * removed from the buffer to allow the object(s) to be added and still * maintain the maximum size or the timeout expires. * * @param buffer the buffer to make bounded, must not be null * @param maximumSize the maximum size * @param timeoutMillis the timeout value in milliseconds, zero or less for no timeout * @return a bounded buffer backed by the given buffer * @throws IllegalArgumentException if the given buffer is null * @since Commons Collections 3.2 */ public static Buffer boundedBuffer(Buffer buffer, int maximumSize, long timeoutMillis) { return BoundedBuffer.decorate(buffer, maximumSize, timeoutMillis); } /** * 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 */ 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); } } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/Closure.java0000644000175000017500000000357310777673522027621 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; /** * 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. * * @since Commons Collections 1.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author James Strachan * @author Nicola Ken Barozzi * @author Stephen Colebourne */ 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(Object input); } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/ClosureUtils.java0000644000175000017500000003646210777673522030645 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; import java.util.Collection; import java.util.Iterator; import java.util.Map; import org.apache.commons.collections.functors.ChainedClosure; import org.apache.commons.collections.functors.EqualPredicate; import org.apache.commons.collections.functors.ExceptionClosure; import org.apache.commons.collections.functors.ForClosure; import org.apache.commons.collections.functors.IfClosure; import org.apache.commons.collections.functors.InvokerTransformer; import org.apache.commons.collections.functors.NOPClosure; import org.apache.commons.collections.functors.SwitchClosure; import org.apache.commons.collections.functors.TransformerClosure; import org.apache.commons.collections.functors.WhileClosure; /** * 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. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne * @author Matt Benson */ 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. * * @see org.apache.commons.collections.functors.ExceptionClosure * * @return the closure */ public static Closure exceptionClosure() { return ExceptionClosure.INSTANCE; } /** * Gets a Closure that will do nothing. * This could be useful during testing as a placeholder. * * @see org.apache.commons.collections.functors.NOPClosure * * @return the closure */ 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. * * @see org.apache.commons.collections.functors.TransformerClosure * * @param transformer the transformer to run each time in the closure, null means nop * @return the closure */ 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. * * @see org.apache.commons.collections.functors.ForClosure * * @param count the number of times to loop * @param closure the closure to call repeatedly * @return the for closure */ 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. * * @see org.apache.commons.collections.functors.WhileClosure * * @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 */ 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. * * @see org.apache.commons.collections.functors.WhileClosure * * @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 */ 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. * * @see org.apache.commons.collections.functors.InvokerTransformer * @see org.apache.commons.collections.functors.TransformerClosure * * @param methodName the name of the method * @return the invoker closure * @throws IllegalArgumentException if the method name is null */ 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. * * @see org.apache.commons.collections.functors.InvokerTransformer * @see org.apache.commons.collections.functors.TransformerClosure * * @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 */ 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. * * @see org.apache.commons.collections.functors.ChainedClosure * * @param closure1 the first closure * @param closure2 the second closure * @return the chained closure * @throws IllegalArgumentException if either closure is null */ 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. * * @see org.apache.commons.collections.functors.ChainedClosure * * @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 */ 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. * * @see org.apache.commons.collections.functors.ChainedClosure * * @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 */ public static Closure chainedClosure(Collection closures) { return ChainedClosure.getInstance(closures); } /** * Create a new Closure that calls another closure based on the * result of the specified predicate. * * @see org.apache.commons.collections.functors.IfClosure * * @param predicate the validating predicate * @param trueClosure the closure called if the predicate is true * @return the if closure * @throws IllegalArgumentException if the predicate is null * @throws IllegalArgumentException if the closure is null * @since Commons Collections 3.2 */ public static Closure ifClosure(Predicate predicate, Closure trueClosure) { return IfClosure.getInstance(predicate, trueClosure); } /** * Create a new Closure that calls one of two closures depending * on the specified predicate. * * @see org.apache.commons.collections.functors.IfClosure * * @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 */ 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. * * @see org.apache.commons.collections.functors.SwitchClosure * * @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 */ 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. * * @see org.apache.commons.collections.functors.SwitchClosure * * @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 */ 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. * * @see org.apache.commons.collections.functors.SwitchClosure * * @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 */ public static Closure switchClosure(Map 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. * * @see org.apache.commons.collections.functors.SwitchClosure * * @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 */ 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); } } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/CollectionUtils.java0000644000175000017500000014237410777673521031323 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Collection; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.Set; import org.apache.commons.collections.collection.PredicatedCollection; import org.apache.commons.collections.collection.SynchronizedCollection; import org.apache.commons.collections.collection.TransformedCollection; import org.apache.commons.collections.collection.TypedCollection; import org.apache.commons.collections.collection.UnmodifiableBoundedCollection; import org.apache.commons.collections.collection.UnmodifiableCollection; /** * Provides utility methods and decorators for {@link Collection} instances. * * @since Commons Collections 1.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @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 Jon Schewe * @author Neil O'Toole * @author Stephen Smith */ 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 collections * @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()) { Object obj = it.next(); for(int i=0,m=Math.max(getFreq(obj,mapa),getFreq(obj,mapb));i * 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 collections * @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()) { Object obj = it.next(); for(int i=0,m=Math.min(getFreq(obj,mapa),getFreq(obj,mapb));i * 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 collections */ 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()) { Object obj = it.next(); for(int i=0,m=((Math.max(getFreq(obj,mapa),getFreq(obj,mapb)))-(Math.min(getFreq(obj,mapa),getFreq(obj,mapb))));ia - 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 collection to subtract, must not be null * @return a new collection with the results * @see Collection#removeAll */ public static Collection subtract(final Collection a, final Collection b) { ArrayList list = new ArrayList( a ); for (Iterator it = b.iterator(); it.hasNext();) { list.remove(it.next()); } return list; } /** * Returns true iff at least one element is in both collections. *

      * 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 collections is non-empty * @since 2.1 * @see #intersection */ 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; } /** * Returns a {@link Map} mapping each unique element in the given * {@link Collection} to an {@link Integer} representing the number * of occurrences of that element in the {@link Collection}. *

      * Only those elements present in the collection will appear as * keys in the map. * * @param coll the collection to get the cardinality map for, must not be null * @return the populated cardinality map */ public static Map getCardinalityMap(final Collection coll) { Map count = new HashMap(); for (Iterator it = coll.iterator(); it.hasNext();) { Object obj = it.next(); Integer c = (Integer) (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 Collection a, final Collection b) { Map mapa = getCardinalityMap(a); Map mapb = getCardinalityMap(b); Iterator it = a.iterator(); while (it.hasNext()) { Object obj = it.next(); 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 collections 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(Object 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 collection which matches the given predicate. *

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

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

      * If the input collection or predicate is null, there is no change made. * * @param collection the collection to get the input from, may be null * @param predicate the predicate to use as a filter, may be null */ public static void filter(Collection collection, Predicate predicate) { if (collection != null && predicate != null) { for (Iterator it = collection.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 inputCollection 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(Collection inputCollection, Predicate predicate) { int count = 0; if (inputCollection != null && predicate != null) { for (Iterator it = inputCollection.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 collection. *

      * A null collection or predicate returns false. * * @param collection the collection 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 collection matches the predicate */ public static boolean exists(Collection collection, Predicate predicate) { if (collection != null && predicate != null) { for (Iterator it = collection.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) { ArrayList answer = new ArrayList(inputCollection.size()); select(inputCollection, predicate, answer); return answer; } /** * 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 void select(Collection inputCollection, Predicate predicate, Collection outputCollection) { if (inputCollection != null && predicate != null) { for (Iterator iter = inputCollection.iterator(); iter.hasNext();) { Object item = iter.next(); if (predicate.evaluate(item)) { outputCollection.add(item); } } } } /** * 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 inputCollection 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 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 void selectRejected(Collection inputCollection, Predicate predicate, Collection outputCollection) { if (inputCollection != null && predicate != null) { for (Iterator iter = inputCollection.iterator(); iter.hasNext();) { Object 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 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 Collection collect(Collection inputCollection, final Transformer transformer, final Collection 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 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 Collection collect(Iterator inputIterator, final Transformer transformer, final Collection outputCollection) { if (inputIterator != null && transformer != null) { while (inputIterator.hasNext()) { Object item = inputIterator.next(); Object value = transformer.transform(item); outputCollection.add(value); } } return outputCollection; } //----------------------------------------------------------------------- /** * Adds an element to the collection unless the element is null. * * @param collection the collection to add to, must not be null * @param object the object to add, if null it will not be added * @return true if the collection changed * @throws NullPointerException if the collection is null * @since Commons Collections 3.2 */ public static boolean addIgnoreNull(Collection collection, Object object) { return (object == null ? false : collection.add(object)); } /** * Adds all elements in the iteration to the given collection. * * @param collection the collection to add to, must not be null * @param iterator the iterator of elements to add, must 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. * * @param collection the collection to add to, must not be null * @param enumeration the enumeration of elements to add, must 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, must not be null * @param elements the array of elements to add, must not be null * @throws NullPointerException if the collection or array is null */ public static void addAll(Collection collection, Object[] 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; } /** * Checks if the specified collection/array/iterator is empty. *

      * This method can handles objects as follows *

        *
      • Collection - via collection isEmpty *
      • Map - via map isEmpty *
      • Array - using array size *
      • Iterator - via hasNext *
      • Enumeration - via hasMoreElements *
      *

      * Note: This method is named to avoid clashing with * {@link #isEmpty(Collection)}. * * @param object the object to get the size of, not null * @return true if empty * @throws IllegalArgumentException thrown if object is not recognised or null * @since Commons Collections 3.2 */ public static boolean sizeIsEmpty(Object object) { if (object instanceof Collection) { return ((Collection) object).isEmpty(); } else if (object instanceof Map) { return ((Map) object).isEmpty(); } else if (object instanceof Object[]) { return ((Object[]) object).length == 0; } else if (object instanceof Iterator) { return ((Iterator) object).hasNext() == false; } else if (object instanceof Enumeration) { return ((Enumeration) object).hasMoreElements() == false; } else if (object == null) { throw new IllegalArgumentException("Unsupported object type: null"); } else { try { return Array.getLength(object) == 0; } catch (IllegalArgumentException ex) { throw new IllegalArgumentException("Unsupported object type: " + object.getClass().getName()); } } } //----------------------------------------------------------------------- /** * Null-safe check if the specified collection is empty. *

      * Null returns true. * * @param coll the collection to check, may be null * @return true if empty or null * @since Commons Collections 3.2 */ public static boolean isEmpty(Collection coll) { return (coll == null || coll.isEmpty()); } /** * Null-safe check if the specified collection is not empty. *

      * Null returns false. * * @param coll the collection to check, may be null * @return true if non-null and non-empty * @since Commons Collections 3.2 */ public static boolean isNotEmpty(Collection coll) { return !CollectionUtils.isEmpty(coll); } //----------------------------------------------------------------------- /** * 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 collection containing all the elements in collection * that are also in retain. The cardinality of an element e * in the returned collection is the same as the cardinality of e * in collection unless retain does not contain e, in which * case the cardinality is zero. This method is useful if you do not wish to modify * the collection c and thus cannot call c.retainAll(retain);. * * @param collection the collection whose contents are the target of the #retailAll operation * @param retain the collection containing the elements to be retained in the returned collection * @return a Collection containing all the elements of collection * that occur at least once in retain. * @throws NullPointerException if either parameter is null * @since Commons Collections 3.2 */ public static Collection retainAll(Collection collection, Collection retain) { return ListUtils.retainAll(collection, retain); } /** * Removes the elements in remove from collection. That is, this * method returns a collection containing all the elements in c * that are not in remove. The cardinality of an element e * in the returned collection is the same as the cardinality of e * in collection unless remove contains e, in which * case the cardinality is zero. This method is useful if you do not wish to modify * the collection c and thus cannot call collection.removeAll(remove);. * * @param collection the collection from which items are removed (in the returned collection) * @param remove the items to be removed from the returned collection * @return a Collection containing all the elements of collection except * any elements that also occur in remove. * @throws NullPointerException if either parameter is null * @since Commons Collections 3.2 */ public static Collection removeAll(Collection collection, Collection remove) { return ListUtils.retainAll(collection, remove); } //----------------------------------------------------------------------- /** * 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 */ 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); } } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/ComparatorUtils.java0000644000175000017500000002247410777673522031336 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; import java.util.Collection; import java.util.Comparator; import org.apache.commons.collections.comparators.BooleanComparator; import org.apache.commons.collections.comparators.ComparableComparator; import org.apache.commons.collections.comparators.ComparatorChain; import org.apache.commons.collections.comparators.NullComparator; import org.apache.commons.collections.comparators.ReverseComparator; import org.apache.commons.collections.comparators.TransformingComparator; /** * 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. * * @since Commons Collections 2.1 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Paul Jack * @author Stephen Colebourne */ 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 Object min(Object o1, Object 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 Object max(Object o1, Object o2, Comparator comparator) { if (comparator == null) { comparator = NATURAL_COMPARATOR; } int c = comparator.compare(o1, o2); return (c > 0) ? o1 : o2; } } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/CursorableLinkedList.java0000644000175000017500000014012610777673521032264 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Collection; import java.util.ConcurrentModificationException; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.NoSuchElementException; import java.lang.ref.WeakReference; /** * A doubly-linked list implementation of the {@link List} interface, * supporting a {@link ListIterator} that allows concurrent modifications * to the underlying list. *

      * Implements all of the optional {@link List} operations, the * stack/queue/dequeue operations available in {@link java.util.LinkedList} * and supports a {@link ListIterator} that allows concurrent modifications * to the underlying list (see {@link #cursor}). *

      * Note that this implementation is not synchronized. * * @deprecated Use new version in list subpackage, which has been rewritten * and now returns the cursor from the listIterator method. Will be removed in v4.0 * @see java.util.LinkedList * @since Commons Collections 1.0 * @version $Revision: 647116 $ $Date: 2008-04-11 12:23:08 +0100 (Fri, 11 Apr 2008) $ * * @author Rodney Waldhoff * @author Janek Bogucki * @author Simon Kitching */ public class CursorableLinkedList implements List, Serializable { /** Ensure serialization compatibility */ private static final long serialVersionUID = 8836393098519411393L; //--- public methods --------------------------------------------- /** * Appends the specified element to the end of this list. * * @param o element to be appended to this list. * @return true */ public boolean add(Object o) { insertListable(_head.prev(),null,o); return true; } /** * Inserts the specified element at the specified position in this list. * Shifts the element currently at that position (if any) and any subsequent * elements to the right (adds one to their indices). * * @param index index at which the specified element is to be inserted. * @param element element to be inserted. * * @throws ClassCastException if the class of the specified element * prevents it from being added to this list. * @throws IllegalArgumentException if some aspect of the specified * element prevents it from being added to this list. * @throws IndexOutOfBoundsException if the index is out of range * (index < 0 || index > size()). */ public void add(int index, Object element) { if(index == _size) { add(element); } else { if(index < 0 || index > _size) { throw new IndexOutOfBoundsException(String.valueOf(index) + " < 0 or " + String.valueOf(index) + " > " + _size); } Listable succ = (isEmpty() ? null : getListableAt(index)); Listable pred = (null == succ ? null : succ.prev()); insertListable(pred,succ,element); } } /** * Appends all of the elements in the specified collection to the end of * this list, in the order that they are returned by the specified * {@link Collection}'s {@link Iterator}. The behavior of this operation is * unspecified if the specified collection is modified while * the operation is in progress. (Note that this will occur if the * specified collection is this list, and it's nonempty.) * * @param c collection whose elements are to be added to this list. * @return true if this list changed as a result of the call. * * @throws ClassCastException if the class of an element in the specified * collection prevents it from being added to this list. * @throws IllegalArgumentException if some aspect of an element in the * specified collection prevents it from being added to this * list. */ public boolean addAll(Collection c) { if(c.isEmpty()) { return false; } Iterator it = c.iterator(); while(it.hasNext()) { insertListable(_head.prev(),null,it.next()); } return true; } /** * Inserts all of the elements in the specified collection into this * list at the specified position. Shifts the element currently at * that position (if any) and any subsequent elements to the right * (increases their indices). The new elements will appear in this * list in the order that they are returned by the specified * {@link Collection}'s {@link Iterator}. The behavior of this operation is * unspecified if the specified collection is modified while the * operation is in progress. (Note that this will occur if the specified * collection is this list, and it's nonempty.) * * @param index index at which to insert first element from the specified * collection. * @param c elements to be inserted into this list. * @return true if this list changed as a result of the call. * * @throws ClassCastException if the class of one of elements of the * specified collection prevents it from being added to this * list. * @throws IllegalArgumentException if some aspect of one of elements of * the specified collection prevents it from being added to * this list. * @throws IndexOutOfBoundsException if the index is out of range (index * < 0 || index > size()). */ public boolean addAll(int index, Collection c) { if(c.isEmpty()) { return false; } else if(_size == index || _size == 0) { return addAll(c); } else { Listable succ = getListableAt(index); Listable pred = (null == succ) ? null : succ.prev(); Iterator it = c.iterator(); while(it.hasNext()) { pred = insertListable(pred,succ,it.next()); } return true; } } /** * Inserts the specified element at the beginning of this list. * (Equivalent to {@link #add(int,java.lang.Object) add(0,o)}). * * @param o element to be prepended to this list. * @return true */ public boolean addFirst(Object o) { insertListable(null,_head.next(),o); return true; } /** * Inserts the specified element at the end of this list. * (Equivalent to {@link #add(java.lang.Object)}). * * @param o element to be appended to this list. * @return true */ public boolean addLast(Object o) { insertListable(_head.prev(),null,o); return true; } /** * Removes all of the elements from this list. This * list will be empty after this call returns (unless * it throws an exception). */ public void clear() { /* // this is the quick way, but would force us // to break all the cursors _modCount++; _head.setNext(null); _head.setPrev(null); _size = 0; */ Iterator it = iterator(); while(it.hasNext()) { it.next(); it.remove(); } } /** * Returns true if this list contains the specified element. * More formally, returns true if and only if this list contains * at least one element e such that * (o==null ? e==null : o.equals(e)). * * @param o element whose presence in this list is to be tested. * @return true if this list contains the specified element. */ public boolean contains(Object o) { for(Listable elt = _head.next(), past = null; null != elt && past != _head.prev(); elt = (past = elt).next()) { if((null == o && null == elt.value()) || (o != null && o.equals(elt.value()))) { return true; } } return false; } /** * Returns true if this list contains all of the elements of the * specified collection. * * @param c collection to be checked for containment in this list. * @return true if this list contains all of the elements of the * specified collection. */ public boolean containsAll(Collection c) { Iterator it = c.iterator(); while(it.hasNext()) { if(!this.contains(it.next())) { return false; } } return true; } /** * Returns a {@link ListIterator} for iterating through the * elements of this list. Unlike {@link #iterator}, a cursor * is not bothered by concurrent modifications to the * underlying list. *

      * Specifically, when elements are added to the list before or * after the cursor, the cursor simply picks them up automatically. * 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--i.e., it cannot be removed). *

      * Note that the returned {@link ListIterator} does not support the * {@link ListIterator#nextIndex} and {@link ListIterator#previousIndex} * methods (they throw {@link UnsupportedOperationException} when invoked. *

      * Historical Note: In previous versions of this class, the object * returned from this method was required to be explicitly closed. This * is no longer necessary. * * @see #cursor(int) * @see #listIterator * @see CursorableLinkedList.Cursor */ public CursorableLinkedList.Cursor cursor() { return new Cursor(0); } /** * Returns a {@link ListIterator} for iterating through the * elements of this list, initialized such that * {@link ListIterator#next} will return the element at * the specified index (if any) and {@link ListIterator#previous} * will return the element immediately preceding it (if any). * Unlike {@link #iterator}, a cursor * is not bothered by concurrent modifications to the * underlying list. * * @see #cursor * @see #listIterator(int) * @see CursorableLinkedList.Cursor * @throws IndexOutOfBoundsException if the index is out of range (index * < 0 || index > size()). */ public CursorableLinkedList.Cursor cursor(int i) { return new Cursor(i); } /** * Compares the specified object with this list for equality. Returns * true if and only if the specified object is also a list, 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. * * @param o the object to be compared for equality with this list. * @return true if the specified object is equal to this list. */ public boolean equals(Object o) { if(o == this) { return true; } else if(!(o instanceof List)) { return false; } Iterator it = ((List)o).listIterator(); for(Listable elt = _head.next(), past = null; null != elt && past != _head.prev(); elt = (past = elt).next()) { if(!it.hasNext() || (null == elt.value() ? null != it.next() : !(elt.value().equals(it.next()))) ) { return false; } } return !it.hasNext(); } /** * Returns the element at the specified position in this list. * * @param index index of element to return. * @return the element at the specified position in this list. * * @throws IndexOutOfBoundsException if the index is out of range (index * < 0 || index >= size()). */ public Object get(int index) { return getListableAt(index).value(); } /** * Returns the element at the beginning of this list. */ public Object getFirst() { try { return _head.next().value(); } catch(NullPointerException e) { throw new NoSuchElementException(); } } /** * Returns the element at the end of this list. */ public Object getLast() { try { return _head.prev().value(); } catch(NullPointerException e) { throw new NoSuchElementException(); } } /** * Returns the hash code value for this list. The hash code of a list * is defined to be the result of the following calculation: *

           *  hashCode = 1;
           *  Iterator i = list.iterator();
           *  while (i.hasNext()) {
           *      Object obj = i.next();
           *      hashCode = 31*hashCode + (obj==null ? 0 : obj.hashCode());
           *  }
           * 
      * This ensures that list1.equals(list2) implies that * list1.hashCode()==list2.hashCode() for any two lists, * list1 and list2, as required by the general * contract of Object.hashCode. * * @return the hash code value for this list. * @see Object#hashCode() * @see Object#equals(Object) * @see #equals(Object) */ public int hashCode() { int hash = 1; for(Listable elt = _head.next(), past = null; null != elt && past != _head.prev(); elt = (past = elt).next()) { hash = 31*hash + (null == elt.value() ? 0 : elt.value().hashCode()); } return hash; } /** * Returns the index in this list of the first occurrence of the specified * element, or -1 if this list does not contain this element. * More formally, returns the lowest index i such that * (o==null ? get(i)==null : o.equals(get(i))), * or -1 if there is no such index. * * @param o element to search for. * @return the index in this list of the first occurrence of the specified * element, or -1 if this list does not contain this element. */ public int indexOf(Object o) { int ndx = 0; // perform the null check outside of the loop to save checking every // single time through the loop. if (null == o) { for(Listable elt = _head.next(), past = null; null != elt && past != _head.prev(); elt = (past = elt).next()) { if (null == elt.value()) { return ndx; } ndx++; } } else { for(Listable elt = _head.next(), past = null; null != elt && past != _head.prev(); elt = (past = elt).next()) { if (o.equals(elt.value())) { return ndx; } ndx++; } } return -1; } /** * Returns true if this list contains no elements. * @return true if this list contains no elements. */ public boolean isEmpty() { return(0 == _size); } /** * Returns a fail-fast iterator. * @see List#iterator */ public Iterator iterator() { return listIterator(0); } /** * Returns the index in this list of the last occurrence of the specified * element, or -1 if this list does not contain this element. * More formally, returns the highest index i such that * (o==null ? get(i)==null : o.equals(get(i))), * or -1 if there is no such index. * * @param o element to search for. * @return the index in this list of the last occurrence of the specified * element, or -1 if this list does not contain this element. */ public int lastIndexOf(Object o) { int ndx = _size-1; // perform the null check outside of the loop to save checking every // single time through the loop. if (null == o) { for(Listable elt = _head.prev(), past = null; null != elt && past != _head.next(); elt = (past = elt).prev()) { if (null == elt.value()) { return ndx; } ndx--; } } else { for(Listable elt = _head.prev(), past = null; null != elt && past != _head.next(); elt = (past = elt).prev()) { if (o.equals(elt.value())) { return ndx; } ndx--; } } return -1; } /** * Returns a fail-fast ListIterator. * @see List#listIterator */ public ListIterator listIterator() { return listIterator(0); } /** * Returns a fail-fast ListIterator. * @see List#listIterator(int) */ public ListIterator listIterator(int index) { if(index<0 || index > _size) { throw new IndexOutOfBoundsException(index + " < 0 or > " + _size); } return new ListIter(index); } /** * Removes the first occurrence in this list of the specified element. * If this list does not contain the element, it is * unchanged. More formally, removes the element with the lowest index i * such that (o==null ? get(i)==null : o.equals(get(i))) (if * such an element exists). * * @param o element to be removed from this list, if present. * @return true if this list contained the specified element. */ public boolean remove(Object o) { for(Listable elt = _head.next(), past = null; null != elt && past != _head.prev(); elt = (past = elt).next()) { if(null == o && null == elt.value()) { removeListable(elt); return true; } else if(o != null && o.equals(elt.value())) { removeListable(elt); return true; } } return false; } /** * Removes the element at the specified position in this list (optional * operation). Shifts any subsequent elements to the left (subtracts one * from their indices). Returns the element that was removed from the * list. * * @param index the index of the element to removed. * @return the element previously at the specified position. * * @throws IndexOutOfBoundsException if the index is out of range (index * < 0 || index >= size()). */ public Object remove(int index) { Listable elt = getListableAt(index); Object ret = elt.value(); removeListable(elt); return ret; } /** * Removes from this list all the elements that are contained in the * specified collection. * * @param c collection that defines which elements will be removed from * this list. * @return true if this list changed as a result of the call. */ public boolean removeAll(Collection c) { if(0 == c.size() || 0 == _size) { return false; } else { boolean changed = false; Iterator it = iterator(); while(it.hasNext()) { if(c.contains(it.next())) { it.remove(); changed = true; } } return changed; } } /** * Removes the first element of this list, if any. */ public Object removeFirst() { if(_head.next() != null) { Object val = _head.next().value(); removeListable(_head.next()); return val; } else { throw new NoSuchElementException(); } } /** * Removes the last element of this list, if any. */ public Object removeLast() { if(_head.prev() != null) { Object val = _head.prev().value(); removeListable(_head.prev()); return val; } else { throw new NoSuchElementException(); } } /** * Retains only the elements in this list that are contained in the * specified collection. In other words, removes * from this list all the elements that are not contained in the specified * collection. * * @param c collection that defines which elements this set will retain. * * @return true if this list changed as a result of the call. */ public boolean retainAll(Collection c) { boolean changed = false; Iterator it = iterator(); while(it.hasNext()) { if(!c.contains(it.next())) { it.remove(); changed = true; } } return changed; } /** * Replaces the element at the specified position in this list with the * specified element. * * @param index index of element to replace. * @param element element to be stored at the specified position. * @return the element previously at the specified position. * * @throws ClassCastException if the class of the specified element * prevents it from being added to this list. * @throws IllegalArgumentException if some aspect of the specified * element prevents it from being added to this list. * @throws IndexOutOfBoundsException if the index is out of range * (index < 0 || index >= size()). */ public Object set(int index, Object element) { Listable elt = getListableAt(index); Object val = elt.setValue(element); broadcastListableChanged(elt); return val; } /** * Returns the number of elements in this list. * @return the number of elements in this list. */ public int size() { return _size; } /** * Returns an array containing all of the elements in this list in proper * sequence. Obeys the general contract of the {@link Collection#toArray} method. * * @return an array containing all of the elements in this list in proper * sequence. */ public Object[] toArray() { Object[] array = new Object[_size]; int i = 0; for(Listable elt = _head.next(), past = null; null != elt && past != _head.prev(); elt = (past = elt).next()) { array[i++] = elt.value(); } return array; } /** * Returns an array containing all of the elements in this list in proper * sequence; the runtime type of the returned array is that of the * specified array. Obeys the general contract of the * {@link Collection#toArray} method. * * @param a the array into which the elements of this list are to * be stored, if it is big enough; otherwise, a new array of the * same runtime type is allocated for this purpose. * @return an array containing the elements of this list. * @exception ArrayStoreException * if the runtime type of the specified array * is not a supertype of the runtime type of every element in * this list. */ public Object[] toArray(Object a[]) { if(a.length < _size) { a = (Object[])Array.newInstance(a.getClass().getComponentType(), _size); } int i = 0; for(Listable elt = _head.next(), past = null; null != elt && past != _head.prev(); elt = (past = elt).next()) { a[i++] = elt.value(); } if(a.length > _size) { a[_size] = null; // should we null out the rest of the array also? java.util.LinkedList doesn't } return a; } /** * Returns a {@link String} representation of this list, suitable for debugging. * @return a {@link String} representation of this list, suitable for debugging. */ public String toString() { StringBuffer buf = new StringBuffer(); buf.append("["); for(Listable elt = _head.next(), past = null; null != elt && past != _head.prev(); elt = (past = elt).next()) { if(_head.next() != elt) { buf.append(", "); } buf.append(elt.value()); } buf.append("]"); return buf.toString(); } /** * Returns a fail-fast sublist. * @see List#subList(int,int) */ public List subList(int i, int j) { if(i < 0 || j > _size || i > j) { throw new IndexOutOfBoundsException(); } else if(i == 0 && j == _size) { return this; } else { return new CursorableSubList(this,i,j); } } //--- protected methods ------------------------------------------ /** * Inserts a new value into my * list, after the specified before element, and before the * specified after element * * @return the newly created * {@link org.apache.commons.collections.CursorableLinkedList.Listable} */ protected Listable insertListable(Listable before, Listable after, Object value) { _modCount++; _size++; Listable elt = new Listable(before,after,value); if(null != before) { before.setNext(elt); } else { _head.setNext(elt); } if(null != after) { after.setPrev(elt); } else { _head.setPrev(elt); } broadcastListableInserted(elt); return elt; } /** * Removes the given * {@link org.apache.commons.collections.CursorableLinkedList.Listable} * from my list. */ protected void removeListable(Listable elt) { _modCount++; _size--; if(_head.next() == elt) { _head.setNext(elt.next()); } if(null != elt.next()) { elt.next().setPrev(elt.prev()); } if(_head.prev() == elt) { _head.setPrev(elt.prev()); } if(null != elt.prev()) { elt.prev().setNext(elt.next()); } broadcastListableRemoved(elt); } /** * Returns the * {@link org.apache.commons.collections.CursorableLinkedList.Listable} * at the specified index. * * @throws IndexOutOfBoundsException if index is less than zero or * greater than or equal to the size of this list. */ protected Listable getListableAt(int index) { if(index < 0 || index >= _size) { throw new IndexOutOfBoundsException(String.valueOf(index) + " < 0 or " + String.valueOf(index) + " >= " + _size); } if(index <=_size/2) { Listable elt = _head.next(); for(int i = 0; i < index; i++) { elt = elt.next(); } return elt; } else { Listable elt = _head.prev(); for(int i = (_size-1); i > index; i--) { elt = elt.prev(); } return elt; } } /** * Registers a {@link CursorableLinkedList.Cursor} to be notified * of changes to this list. */ protected void registerCursor(Cursor cur) { // 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 = (WeakReference) it.next(); if (ref.get() == null) { it.remove(); } } _cursors.add( new WeakReference(cur) ); } /** * Removes a {@link CursorableLinkedList.Cursor} from * the set of cursors to be notified of changes to this list. */ protected void unregisterCursor(Cursor cur) { for (Iterator it = _cursors.iterator(); it.hasNext(); ) { WeakReference ref = (WeakReference) it.next(); Cursor cursor = (Cursor) ref.get(); if (cursor == 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 (cursor == cur) { ref.clear(); it.remove(); break; } } } /** * Informs all of my registered cursors that they are now * invalid. */ protected void invalidateCursors() { Iterator it = _cursors.iterator(); while (it.hasNext()) { WeakReference ref = (WeakReference) it.next(); Cursor cursor = (Cursor) ref.get(); if (cursor != null) { // cursor is null if object has been garbage-collected cursor.invalidate(); ref.clear(); } it.remove(); } } /** * Informs all of my registered cursors that the specified * element was changed. * @see #set(int,java.lang.Object) */ protected void broadcastListableChanged(Listable elt) { 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.listableChanged(elt); } } } /** * Informs all of my registered cursors that the specified * element was just removed from my list. */ protected void broadcastListableRemoved(Listable elt) { 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.listableRemoved(elt); } } } /** * Informs all of my registered cursors that the specified * element was just added to my list. */ protected void broadcastListableInserted(Listable elt) { 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.listableInserted(elt); } } } private void writeObject(ObjectOutputStream out) throws IOException { out.defaultWriteObject(); out.writeInt(_size); Listable cur = _head.next(); while (cur != null) { out.writeObject(cur.value()); cur = cur.next(); } } private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); _size = 0; _modCount = 0; _cursors = new ArrayList(); _head = new Listable(null,null,null); int size = in.readInt(); for (int i=0;i * _head.next() points to the first element in the list, * _head.prev() to the last. Note that it is possible for * _head.next().prev() and _head.prev().next() to be * non-null, as when I am a sublist for some larger list. * Use == _head.next() and == _head.prev() to determine * if a given * {@link org.apache.commons.collections.CursorableLinkedList.Listable} * is the first or last element in the list. */ protected transient Listable _head = new Listable(null,null,null); /** Tracks the number of structural modifications to me. */ protected transient int _modCount = 0; /** * A list of the currently {@link CursorableLinkedList.Cursor}s currently * open in this list. */ protected transient List _cursors = new ArrayList(); //--- inner classes ---------------------------------------------- static class Listable implements Serializable { private Listable _prev = null; private Listable _next = null; private Object _val = null; Listable(Listable prev, Listable next, Object val) { _prev = prev; _next = next; _val = val; } Listable next() { return _next; } Listable prev() { return _prev; } Object value() { return _val; } void setNext(Listable next) { _next = next; } void setPrev(Listable prev) { _prev = prev; } Object setValue(Object val) { Object temp = _val; _val = val; return temp; } } class ListIter implements ListIterator { Listable _cur = null; Listable _lastReturned = null; int _expectedModCount = _modCount; int _nextIndex = 0; ListIter(int index) { if(index == 0) { _cur = new Listable(null,_head.next(),null); _nextIndex = 0; } else if(index == _size) { _cur = new Listable(_head.prev(),null,null); _nextIndex = _size; } else { Listable temp = getListableAt(index); _cur = new Listable(temp.prev(),temp,null); _nextIndex = index; } } public Object previous() { checkForComod(); if(!hasPrevious()) { throw new NoSuchElementException(); } else { Object ret = _cur.prev().value(); _lastReturned = _cur.prev(); _cur.setNext(_cur.prev()); _cur.setPrev(_cur.prev().prev()); _nextIndex--; return ret; } } public boolean hasNext() { checkForComod(); return(null != _cur.next() && _cur.prev() != _head.prev()); } public Object next() { checkForComod(); if(!hasNext()) { throw new NoSuchElementException(); } else { Object ret = _cur.next().value(); _lastReturned = _cur.next(); _cur.setPrev(_cur.next()); _cur.setNext(_cur.next().next()); _nextIndex++; return ret; } } public int previousIndex() { checkForComod(); if(!hasPrevious()) { return -1; } return _nextIndex-1; } public boolean hasPrevious() { checkForComod(); return(null != _cur.prev() && _cur.next() != _head.next()); } public void set(Object o) { checkForComod(); try { _lastReturned.setValue(o); } catch(NullPointerException e) { throw new IllegalStateException(); } } public int nextIndex() { checkForComod(); if(!hasNext()) { return size(); } return _nextIndex; } public void remove() { checkForComod(); if(null == _lastReturned) { throw new IllegalStateException(); } else { _cur.setNext(_lastReturned == _head.prev() ? null : _lastReturned.next()); _cur.setPrev(_lastReturned == _head.next() ? null : _lastReturned.prev()); removeListable(_lastReturned); _lastReturned = null; _nextIndex--; _expectedModCount++; } } public void add(Object o) { checkForComod(); _cur.setPrev(insertListable(_cur.prev(),_cur.next(),o)); _lastReturned = null; _nextIndex++; _expectedModCount++; } protected void checkForComod() { if(_expectedModCount != _modCount) { throw new ConcurrentModificationException(); } } } public class Cursor extends ListIter implements ListIterator { boolean _valid = false; Cursor(int index) { super(index); _valid = true; registerCursor(this); } public int previousIndex() { throw new UnsupportedOperationException(); } public int nextIndex() { throw new UnsupportedOperationException(); } public void add(Object o) { checkForComod(); Listable elt = insertListable(_cur.prev(),_cur.next(),o); _cur.setPrev(elt); _cur.setNext(elt.next()); _lastReturned = null; _nextIndex++; _expectedModCount++; } protected void listableRemoved(Listable elt) { if(null == _head.prev()) { _cur.setNext(null); } else if(_cur.next() == elt) { _cur.setNext(elt.next()); } if(null == _head.next()) { _cur.setPrev(null); } else if(_cur.prev() == elt) { _cur.setPrev(elt.prev()); } if(_lastReturned == elt) { _lastReturned = null; } } protected void listableInserted(Listable elt) { if(null == _cur.next() && null == _cur.prev()) { _cur.setNext(elt); } else if(_cur.prev() == elt.prev()) { _cur.setNext(elt); } if(_cur.next() == elt.next()) { _cur.setPrev(elt); } if(_lastReturned == elt) { _lastReturned = null; } } protected void listableChanged(Listable elt) { if(_lastReturned == elt) { _lastReturned = null; } } protected void checkForComod() { if(!_valid) { throw new ConcurrentModificationException(); } } protected void invalidate() { _valid = false; } /** * 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) { _valid = false; unregisterCursor(this); } } } } /** * @deprecated Use new version in list subpackage, which has been rewritten * and now returns the cursor from the listIterator method. Will be removed in v4.0 */ class CursorableSubList extends CursorableLinkedList implements List { //--- constructors ----------------------------------------------- CursorableSubList(CursorableLinkedList list, int from, int to) { if(0 > from || list.size() < to) { throw new IndexOutOfBoundsException(); } else if(from > to) { throw new IllegalArgumentException(); } _list = list; if(from < list.size()) { _head.setNext(_list.getListableAt(from)); _pre = (null == _head.next()) ? null : _head.next().prev(); } else { _pre = _list.getListableAt(from-1); } if(from == to) { _head.setNext(null); _head.setPrev(null); if(to < list.size()) { _post = _list.getListableAt(to); } else { _post = null; } } else { _head.setPrev(_list.getListableAt(to-1)); _post = _head.prev().next(); } _size = to - from; _modCount = _list._modCount; } //--- public methods ------------------------------------------ public void clear() { checkForComod(); Iterator it = iterator(); while(it.hasNext()) { it.next(); it.remove(); } } public Iterator iterator() { checkForComod(); return super.iterator(); } public int size() { checkForComod(); return super.size(); } public boolean isEmpty() { checkForComod(); return super.isEmpty(); } public Object[] toArray() { checkForComod(); return super.toArray(); } public Object[] toArray(Object a[]) { checkForComod(); return super.toArray(a); } public boolean contains(Object o) { checkForComod(); return super.contains(o); } public boolean remove(Object o) { checkForComod(); return super.remove(o); } public Object removeFirst() { checkForComod(); return super.removeFirst(); } public Object removeLast() { checkForComod(); return super.removeLast(); } public boolean addAll(Collection c) { checkForComod(); return super.addAll(c); } public boolean add(Object o) { checkForComod(); return super.add(o); } public boolean addFirst(Object o) { checkForComod(); return super.addFirst(o); } public boolean addLast(Object o) { checkForComod(); return super.addLast(o); } public boolean removeAll(Collection c) { checkForComod(); return super.removeAll(c); } public boolean containsAll(Collection c) { checkForComod(); return super.containsAll(c); } public boolean addAll(int index, Collection c) { checkForComod(); return super.addAll(index,c); } public int hashCode() { checkForComod(); return super.hashCode(); } public boolean retainAll(Collection c) { checkForComod(); return super.retainAll(c); } public Object set(int index, Object element) { checkForComod(); return super.set(index,element); } public boolean equals(Object o) { checkForComod(); return super.equals(o); } public Object get(int index) { checkForComod(); return super.get(index); } public Object getFirst() { checkForComod(); return super.getFirst(); } public Object getLast() { checkForComod(); return super.getLast(); } public void add(int index, Object element) { checkForComod(); super.add(index,element); } public ListIterator listIterator(int index) { checkForComod(); return super.listIterator(index); } public Object remove(int index) { checkForComod(); return super.remove(index); } public int indexOf(Object o) { checkForComod(); return super.indexOf(o); } public int lastIndexOf(Object o) { checkForComod(); return super.lastIndexOf(o); } public ListIterator listIterator() { checkForComod(); return super.listIterator(); } public List subList(int fromIndex, int toIndex) { checkForComod(); return super.subList(fromIndex,toIndex); } //--- protected methods ------------------------------------------ /** * Inserts a new value into my * list, after the specified before element, and before the * specified after element * * @return the newly created {@link CursorableLinkedList.Listable} */ protected Listable insertListable(Listable before, Listable after, Object value) { _modCount++; _size++; Listable elt = _list.insertListable((null == before ? _pre : before), (null == after ? _post : after),value); if(null == _head.next()) { _head.setNext(elt); _head.setPrev(elt); } if(before == _head.prev()) { _head.setPrev(elt); } if(after == _head.next()) { _head.setNext(elt); } broadcastListableInserted(elt); return elt; } /** * Removes the given {@link CursorableLinkedList.Listable} from my list. */ protected void removeListable(Listable elt) { _modCount++; _size--; if(_head.next() == elt && _head.prev() == elt) { _head.setNext(null); _head.setPrev(null); } if(_head.next() == elt) { _head.setNext(elt.next()); } if(_head.prev() == elt) { _head.setPrev(elt.prev()); } _list.removeListable(elt); broadcastListableRemoved(elt); } /** * Test to see if my underlying list has been modified * by some other process. If it has, throws a * {@link ConcurrentModificationException}, otherwise * quietly returns. * * @throws ConcurrentModificationException */ protected void checkForComod() throws ConcurrentModificationException { if(_modCount != _list._modCount) { throw new ConcurrentModificationException(); } } //--- protected attributes --------------------------------------- /** My underlying list */ protected CursorableLinkedList _list = null; /** The element in my underlying list preceding the first element in my list. */ protected Listable _pre = null; /** The element in my underlying list following the last element in my list. */ protected Listable _post = null; } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/DefaultMapBag.java0000644000175000017500000003300310777673522030630 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; import java.util.ArrayList; import java.util.Collection; import java.util.ConcurrentModificationException; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.commons.collections.set.UnmodifiableSet; /** * A skeletal implementation of the {@link Bag} * interface to minimize the effort required for target implementations. * Subclasses need only to call setMap(Map) in their constructor * (or invoke the Map constructor) specifying a map instance that will be used * to store the contents of the bag. *

      * 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. * * @deprecated Moved to bag subpackage as AbstractMapBag. Due to be removed in v4.0. * @since Commons Collections 2.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Chuck Burdick * @author Michael A. Smith * @author Stephen Colebourne * @author Janek Bogucki */ public abstract class DefaultMapBag implements Bag { private Map _map = null; private int _total = 0; private int _mods = 0; /** * No-argument constructor. * Subclasses should invoke setMap(Map) in * their constructors. */ public DefaultMapBag() { } /** * Constructor that assigns the specified Map as the backing store. * The map must be empty. * * @param map the map to assign */ protected DefaultMapBag(Map map) { setMap(map); } /** * Adds a new element to the bag by 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(Object object) { return add(object, 1); } /** * Adds a new element to the bag by 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(Object object, int nCopies) { _mods++; if (nCopies > 0) { int count = (nCopies + getCount(object)); _map.put(object, new Integer(count)); _total += nCopies; return (count == nCopies); } 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() { _mods++; _map.clear(); _total = 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) { 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 */ public boolean containsAll(Bag other) { boolean result = true; Iterator i = other.uniqueSet().iterator(); while (i.hasNext()) { Object current = i.next(); boolean contains = getCount(current) >= other.getCount(current); result = result && contains; } return result; } /** * Returns true if the given object is not null, has the precise type * of this bag, and contains the same number of occurrences of all the * same elements. * * @param object the object to test for equality * @return true if that object equals this bag */ 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();) { Object element = it.next(); if (other.getCount(element) != getCount(element)) { return false; } } return true; } /** * Returns the hash code of the underlying map. * * @return the hash code of the underlying map */ public int hashCode() { return _map.hashCode(); } /** * Returns true if the underlying map is empty. * * @return true if there are no elements in this bag */ public boolean isEmpty() { return _map.isEmpty(); } public Iterator iterator() { return new BagIterator(this, extractList().iterator()); } static class BagIterator implements Iterator { private DefaultMapBag _parent = null; private Iterator _support = null; private Object _current = null; private int _mods = 0; public BagIterator(DefaultMapBag parent, Iterator support) { _parent = parent; _support = support; _current = null; _mods = parent.modCount(); } public boolean hasNext() { return _support.hasNext(); } public Object next() { if (_parent.modCount() != _mods) { throw new ConcurrentModificationException(); } _current = _support.next(); return _current; } public void remove() { if (_parent.modCount() != _mods) { throw new ConcurrentModificationException(); } _support.remove(); _parent.remove(_current, 1); _mods++; } } public boolean remove(Object object) { return remove(object, getCount(object)); } public boolean remove(Object object, int nCopies) { _mods++; boolean result = false; int count = getCount(object); if (nCopies <= 0) { result = false; } else if (count > nCopies) { _map.put(object, new Integer(count - nCopies)); result = true; _total -= nCopies; } else { // count > 0 && count <= i // need to remove all result = (_map.remove(object) != null); _total -= count; } return result; } public boolean removeAll(Collection coll) { boolean result = false; if (coll != null) { Iterator i = coll.iterator(); while (i.hasNext()) { boolean changed = remove(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) { return retainAll(new HashBag(coll)); } /** * Remove any members of the bag that are not in the given * bag, respecting cardinality. * @see #retainAll(Collection) * * @param other the bag to retain * @return true if this call changed the collection */ public boolean retainAll(Bag other) { boolean result = false; Bag excess = new HashBag(); Iterator i = uniqueSet().iterator(); while (i.hasNext()) { Object 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; } /** * Returns an array of all of this bag's elements. * * @return an array of all of this bag's elements */ public Object[] toArray() { return extractList().toArray(); } /** * 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) { return extractList().toArray(array); } /** * 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(Object object) { int result = 0; Integer count = MapUtils.getInteger(_map, object); if (count != null) { result = count.intValue(); } return result; } /** * Returns an unmodifiable view of the underlying map's key set. * * @return the set of unique elements in this bag */ public Set uniqueSet() { return UnmodifiableSet.decorate(_map.keySet()); } /** * Returns the number of elements in this bag. * * @return the number of elements in this bag */ public int size() { return _total; } /** * Actually walks the bag to make sure the count is correct and * resets the running total * * @return the current total size */ protected int calcTotalSize() { _total = extractList().size(); return _total; } /** * Utility method for implementations to set the map that backs * this bag. Not intended for interactive use outside of * subclasses. */ protected void setMap(Map map) { if (map == null || map.isEmpty() == false) { throw new IllegalArgumentException("The map must be non-null and empty"); } _map = map; } /** * Utility method for implementations to access the map that backs * this bag. Not intended for interactive use outside of * subclasses. */ protected Map getMap() { return _map; } /** * Create a list for use in iteration, etc. */ private List extractList() { List result = new ArrayList(); Iterator i = uniqueSet().iterator(); while (i.hasNext()) { Object current = i.next(); for (int index = getCount(current); index > 0; index--) { result.add(current); } } return result; } /** * Return number of modifications for iterator. * * @return the modification count */ private int modCount() { return _mods; } /** * Implement a toString() method suitable for debugging. * * @return a debugging toString */ public String toString() { StringBuffer buf = new StringBuffer(); buf.append("["); Iterator i = uniqueSet().iterator(); while (i.hasNext()) { Object current = i.next(); int count = getCount(current); buf.append(count); buf.append(":"); buf.append(current); if (i.hasNext()) { buf.append(","); } } buf.append("]"); return buf.toString(); } } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/DefaultMapEntry.java0000644000175000017500000001147710777673521031252 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; import java.util.Map; /** * A default implementation of {@link java.util.Map.Entry} * * @deprecated Use the version in the keyvalue subpackage. Will be removed in v4.0 * @since Commons Collections 1.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author James Strachan * @author Michael A. Smith * @author Neil O'Toole * @author Stephen Colebourne */ public class DefaultMapEntry implements Map.Entry, KeyValue { /** The key */ private Object key; /** The value */ private Object value; /** * Constructs a new DefaultMapEntry with a null key * and null value. */ public DefaultMapEntry() { super(); } /** * Constructs a new DefaultMapEntry with the given * key and given value. * * @param entry the entry to copy, must not be null * @throws NullPointerException if the entry is null */ public DefaultMapEntry(Map.Entry entry) { super(); this.key = entry.getKey(); this.value = entry.getValue(); } /** * Constructs a new DefaultMapEntry 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 */ public DefaultMapEntry(Object key, Object value) { super(); this.key = key; this.value = value; } // Map.Entry interface //------------------------------------------------------------------------- /** * Gets the key from the Map Entry. * * @return the key */ public Object getKey() { return key; } /** * Sets the key stored in this Map Entry. *

      * This Map Entry is not connected to a Map, so only the local data is changed. * * @param key the new key */ public void setKey(Object key) { this.key = key; } /** * Gets the value from the Map Entry. * * @return the value */ public Object getValue() { return value; } /** * 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 Object setValue(Object value) { Object answer = this.value; this.value = value; return answer; } // Basics //----------------------------------------------------------------------- /** * 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()); } /** * Written to match the output of the Map.Entry's used in * a {@link java.util.HashMap}. * @since 3.0 */ public String toString() { return ""+getKey()+"="+getValue(); } } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/DoubleOrderedMap.java0000644000175000017500000020530510777673522031357 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; import java.util.AbstractCollection; import java.util.AbstractMap; import java.util.AbstractSet; import java.util.Collection; import java.util.ConcurrentModificationException; import java.util.Iterator; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; /** * Red-Black tree-based implementation of Map. 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, * particularly when trying to keep the two TreeMaps synchronized with * each other. And if the data contained in the TreeMaps is large, the * cost of redundant storage becomes significant. (See also the new * {@link org.apache.commons.collections.bidimap.DualTreeBidiMap DualTreeBidiMap} and * {@link org.apache.commons.collections.bidimap.DualHashBidiMap DualHashBidiMap} * implementations.) *

      * This solution keeps the data properly synchronized and minimizes * the data storage. The red-black algorithm is based on TreeMap's, * 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. *

      * There are some limitations placed on data kept in this Map. The * biggest one is this: *

      * When performing a put operation, neither the key nor the value may * already exist in the Map. In the java.util Map implementations * (HashMap, TreeMap), you can perform a put with an already mapped * key, and neither cares about duplicate values at all ... but this * implementation's put method with throw an IllegalArgumentException * if either the key or the value is already in the Map. *

      * Obviously, that same restriction (and consequence of failing to * heed that restriction) applies to the putAll method. *

      * The Map.Entry instances returned by the appropriate methods will * not allow setValue() and will throw an * UnsupportedOperationException on attempts to call that method. *

      * New methods are added to take advantage of the fact that values are * kept sorted independently of their keys: *

      * Object getKeyForValue(Object value) is the opposite of get; it * takes a value and returns its key, if any. *

      * Object removeValue(Object value) finds and removes the specified * value and returns the now un-used key. *

      * Set entrySetByValue() returns the Map.Entry's in a Set whose * iterator will iterate over the Map.Entry's in ascending order by * their corresponding values. *

      * Set keySetByValue() returns the keys in a Set whose iterator will * iterate over the keys in ascending order by their corresponding * values. *

      * Collection valuesByValue() returns the values in a Collection whose * iterator will iterate over the values in ascending order. * * @deprecated Replaced by TreeBidiMap in bidimap subpackage. Due to be removed in v4.0. * @see BidiMap * @see org.apache.commons.collections.bidimap.DualTreeBidiMap * @see org.apache.commons.collections.bidimap.DualHashBidiMap * @since Commons Collections 2.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Marc Johnson */ public final class DoubleOrderedMap extends AbstractMap { // final for performance private static final int KEY = 0; private static final int VALUE = 1; 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[] { null, null }; private int nodeCount = 0; private int modifications = 0; private Set[] setOfKeys = new Set[] { null, null }; private Set[] setOfEntries = new Set[] { null, null }; private Collection[] collectionOfValues = new Collection[] { null, null }; /** * Construct a new DoubleOrderedMap */ public DoubleOrderedMap() { } /** * Constructs a new DoubleOrderedMap from an existing Map, with keys and * values sorted * * @param map the map whose mappings are to be placed in this map. * * @throws ClassCastException if the keys in the map are not * Comparable, or are not mutually * comparable; also if the values in * the map are not Comparable, or * are not mutually Comparable * @throws NullPointerException if any key or value in the map * is null * @throws IllegalArgumentException if there are duplicate keys * or duplicate values in the * map */ public DoubleOrderedMap(final Map map) throws ClassCastException, NullPointerException, IllegalArgumentException { putAll(map); } /** * Returns the key to which this map maps the specified value. * Returns null if the map contains no mapping for this value. * * @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 for this map. * @throws NullPointerException if the value is null */ public Object getKeyForValue(final Object value) throws ClassCastException, NullPointerException { return doGet((Comparable) value, VALUE); } /** * Removes the mapping for this value from this map if present * * @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. */ public Object removeValue(final Object value) { return doRemove((Comparable) value, VALUE); } /** * 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.

      * * The difference between this method and entrySet is that * entrySet's iterator() method returns an iterator that iterates * over the mappings in ascending order by key. This method's * iterator method iterates over the mappings in ascending order * by value. * * @return a set view of the mappings contained in this map. */ public Set entrySetByValue() { if (setOfEntries[VALUE] == null) { setOfEntries[VALUE] = new AbstractSet() { public Iterator iterator() { return new DoubleOrderedMapIterator(VALUE) { protected Object doGetNext() { return lastReturnedNode; } }; } public boolean contains(Object o) { if (!(o instanceof Map.Entry)) { return false; } Map.Entry entry = (Map.Entry) o; Object key = entry.getKey(); Node node = lookup((Comparable) entry.getValue(), VALUE); return (node != null) && node.getData(KEY).equals(key); } public boolean remove(Object o) { if (!(o instanceof Map.Entry)) { return false; } Map.Entry entry = (Map.Entry) o; Object key = entry.getKey(); Node node = lookup((Comparable) entry.getValue(), VALUE); if ((node != null) && node.getData(KEY).equals(key)) { doRedBlackDelete(node); return true; } return false; } public int size() { return DoubleOrderedMap.this.size(); } public void clear() { DoubleOrderedMap.this.clear(); } }; } return setOfEntries[VALUE]; } /** * 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.

      * * The difference between this method and keySet is that keySet's * iterator() method returns an iterator that iterates over the * keys in ascending order by key. This method's iterator method * iterates over the keys in ascending order by value. * * @return a set view of the keys contained in this map. */ public Set keySetByValue() { if (setOfKeys[VALUE] == null) { setOfKeys[VALUE] = new AbstractSet() { public Iterator iterator() { return new DoubleOrderedMapIterator(VALUE) { protected Object doGetNext() { return lastReturnedNode.getData(KEY); } }; } public int size() { return DoubleOrderedMap.this.size(); } public boolean contains(Object o) { return containsKey(o); } public boolean remove(Object o) { int oldnodeCount = nodeCount; DoubleOrderedMap.this.remove(o); return nodeCount != oldnodeCount; } public void clear() { DoubleOrderedMap.this.clear(); } }; } return setOfKeys[VALUE]; } /** * 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.

      * * The difference between this method and values is that values's * iterator() method returns an iterator that iterates over the * values in ascending order by key. This method's iterator method * iterates over the values in ascending order by key. * * @return a collection view of the values contained in this map. */ public Collection valuesByValue() { if (collectionOfValues[VALUE] == null) { collectionOfValues[VALUE] = new AbstractCollection() { public Iterator iterator() { return new DoubleOrderedMapIterator(VALUE) { protected Object doGetNext() { return lastReturnedNode.getData(VALUE); } }; } public int size() { return DoubleOrderedMap.this.size(); } public boolean contains(Object o) { return containsValue(o); } public boolean remove(Object o) { int oldnodeCount = nodeCount; removeValue(o); return nodeCount != oldnodeCount; } public boolean removeAll(Collection c) { boolean modified = false; Iterator iter = c.iterator(); while (iter.hasNext()) { if (removeValue(iter.next()) != null) { modified = true; } } return modified; } public void clear() { DoubleOrderedMap.this.clear(); } }; } return collectionOfValues[VALUE]; } /** * common remove logic (remove by key or remove by value) * * @param o the key, or value, that we're looking for * @param index KEY or 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 Object doRemove(final Comparable o, final int index) { Node node = lookup(o, index); Object rval = null; if (node != null) { rval = node.getData(oppositeIndex(index)); doRedBlackDelete(node); } return rval; } /** * common get logic, used to get by key or get by value * * @param o the key or value that we're looking for * @param index KEY or VALUE * * @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 Object doGet(final Comparable o, final int index) { checkNonNullComparable(o, index); Node node = lookup(o, index); return ((node == null) ? null : node.getData(oppositeIndex(index))); } /** * Get the opposite index of the specified index * * @param index KEY or VALUE * * @return VALUE (if KEY was specified), else KEY */ private 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; } /** * do the actual lookup of a piece of data * * @param data the key or value to be looked up * @param index KEY or VALUE * * @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; } /** * 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. very useful for starting * a sorting iterator ... * * @param node the node from which we will start searching * @param index KEY or VALUE * * @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; } /** * get the next larger node from the specified node * * @param node the node to be searched from * @param index KEY or VALUE * * @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; } /** * 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 KEY or VALUE */ 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 KEY or VALUE */ 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 KEY or VALUE */ 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 KEY or VALUE */ 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 KEY or VALUE */ 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 KEY or VALUE */ 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 KEY or VALUE */ 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 KEY or VALUE */ 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 KEY or VALUE */ 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 KEY or VALUE */ 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 KEY or VALUE */ 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 KEY or VALUE */ 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 KEY or VALUE */ 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 KEY or VALUE */ 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 KEY or VALUE */ 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 KEY or VALUE */ 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 * @param index KEY or VALUE (used to put the right word in the * exception message) * * @throws NullPointerException if o is null * @throws ClassCastException if o is not Comparable */ private static void checkNonNullComparable(final Object o, final int index) { if (o == null) { throw new NullPointerException(dataName[index] + " cannot be null"); } if (!(o instanceof Comparable)) { throw new ClassCastException(dataName[index] + " 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, 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, 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; } } } } /* ********** START implementation of Map ********** */ /** * Returns the number of key-value mappings in this map. If the * map contains more than Integer.MAXVALUE elements, returns * Integer.MAXVALUE. * * @return the number of key-value mappings in this map. */ public int size() { return nodeCount; } /** * Returns true if this map contains a mapping for the specified * key. * * @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. * @throws NullPointerException if the key is null */ public boolean containsKey(final Object key) throws ClassCastException, NullPointerException { checkKey(key); return lookup((Comparable) key, KEY) != null; } /** * Returns true if this map maps one or more keys to the * specified value. * * @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. */ public boolean containsValue(final Object value) { checkValue(value); return lookup((Comparable) value, VALUE) != null; } /** * Returns the value to which this map maps the specified * key. Returns null if the map contains no mapping for this key. * * @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. * @throws NullPointerException if the key is null */ public Object get(final Object key) throws ClassCastException, NullPointerException { return doGet((Comparable) key, KEY); } /** * Associates the specified value with the specified key in this * map. * * @param key key with which the specified value is to be * associated. * @param value value to be associated with the specified key. * * @return null * * @throws ClassCastException if the class of the specified key * or value prevents it from being * stored in this map. * @throws NullPointerException if the specified key or value * is null * @throws IllegalArgumentException if the key duplicates an * existing key, or if the * value duplicates an * existing value */ public Object put(final Object key, final Object value) throws ClassCastException, NullPointerException, IllegalArgumentException { checkKeyAndValue(key, value); Node node = rootNode[KEY]; if (node == null) { Node root = new Node((Comparable) key, (Comparable) value); rootNode[KEY] = root; rootNode[VALUE] = root; grow(); } else { while (true) { int cmp = compare((Comparable) key, node.getData(KEY)); if (cmp == 0) { 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((Comparable) key, (Comparable) 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((Comparable) key, (Comparable) value); insertValue(newNode); node.setRight(newNode, KEY); newNode.setParent(node, KEY); doRedBlackInsert(newNode, KEY); grow(); break; } } } } return null; } /** * Removes the mapping for this key from this map if present * * @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. */ public Object remove(final Object key) { return doRemove((Comparable) key, KEY); } /** * Removes all mappings from this map */ public void clear() { modify(); nodeCount = 0; rootNode[KEY] = null; rootNode[VALUE] = null; } /** * 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. * * @return a set view of the keys contained in this map. */ public Set keySet() { if (setOfKeys[KEY] == null) { setOfKeys[KEY] = new AbstractSet() { public Iterator iterator() { return new DoubleOrderedMapIterator(KEY) { protected Object doGetNext() { return lastReturnedNode.getData(KEY); } }; } public int size() { return DoubleOrderedMap.this.size(); } public boolean contains(Object o) { return containsKey(o); } public boolean remove(Object o) { int oldNodeCount = nodeCount; DoubleOrderedMap.this.remove(o); return nodeCount != oldNodeCount; } public void clear() { DoubleOrderedMap.this.clear(); } }; } return setOfKeys[KEY]; } /** * 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() { if (collectionOfValues[KEY] == null) { collectionOfValues[KEY] = new AbstractCollection() { public Iterator iterator() { return new DoubleOrderedMapIterator(KEY) { protected Object doGetNext() { return lastReturnedNode.getData(VALUE); } }; } public int size() { return DoubleOrderedMap.this.size(); } public boolean contains(Object o) { return containsValue(o); } public boolean remove(Object o) { int oldNodeCount = nodeCount; removeValue(o); return nodeCount != oldNodeCount; } public boolean removeAll(Collection c) { boolean modified = false; Iterator iter = c.iterator(); while (iter.hasNext()) { if (removeValue(iter.next()) != null) { modified = true; } } return modified; } public void clear() { DoubleOrderedMap.this.clear(); } }; } return collectionOfValues[KEY]; } /** * 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. * The setValue method is not supported on the Map Entry. * * @return a set view of the mappings contained in this map. */ public Set entrySet() { if (setOfEntries[KEY] == null) { setOfEntries[KEY] = new AbstractSet() { public Iterator iterator() { return new DoubleOrderedMapIterator(KEY) { protected Object doGetNext() { return lastReturnedNode; } }; } public boolean contains(Object o) { if (!(o instanceof Map.Entry)) { return false; } Map.Entry entry = (Map.Entry) o; Object value = entry.getValue(); Node node = lookup((Comparable) entry.getKey(), KEY); return (node != null) && node.getData(VALUE).equals(value); } public boolean remove(Object o) { if (!(o instanceof Map.Entry)) { return false; } Map.Entry entry = (Map.Entry) o; Object value = entry.getValue(); Node node = lookup((Comparable) entry.getKey(), KEY); if ((node != null) && node.getData(VALUE).equals(value)) { doRedBlackDelete(node); return true; } return false; } public int size() { return DoubleOrderedMap.this.size(); } public void clear() { DoubleOrderedMap.this.clear(); } }; } return setOfEntries[KEY]; } /* ********** END implementation of Map ********** */ private abstract class DoubleOrderedMapIterator implements Iterator { private int expectedModifications; protected Node lastReturnedNode; private Node nextNode; private int iteratorType; /** * Constructor * * @param type */ DoubleOrderedMapIterator(final int type) { iteratorType = type; expectedModifications = DoubleOrderedMap.this.modifications; lastReturnedNode = null; nextNode = leastNode(rootNode[iteratorType], iteratorType); } /** * @return 'next', whatever that means for a given kind of * DoubleOrderedMapIterator */ protected abstract Object doGetNext(); /* ********** START implementation of Iterator ********** */ /** * @return true if the iterator has more elements. */ public final boolean hasNext() { return nextNode != null; } /** * @return the next element in the iteration. * * @throws NoSuchElementException if iteration has no more * elements. * @throws ConcurrentModificationException if the * DoubleOrderedMap is * modified behind * the iterator's * back */ public final Object next() throws NoSuchElementException, ConcurrentModificationException { if (nextNode == null) { throw new NoSuchElementException(); } if (modifications != expectedModifications) { throw new ConcurrentModificationException(); } lastReturnedNode = nextNode; nextNode = nextGreater(nextNode, iteratorType); return doGetNext(); } /** * Removes from the underlying collection the last element * returned by the iterator. This method can be called only * once per call to next. The behavior of an iterator is * unspecified if the underlying collection is modified while * the iteration is in progress in any way other than by * calling this method. * * @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 ConcurrentModificationException if the * DoubleOrderedMap is * modified behind * the iterator's * back */ public final void remove() throws IllegalStateException, ConcurrentModificationException { if (lastReturnedNode == null) { throw new IllegalStateException(); } if (modifications != expectedModifications) { throw new ConcurrentModificationException(); } doRedBlackDelete(lastReturnedNode); expectedModifications++; lastReturnedNode = null; } /* ********** END implementation of Iterator ********** */ } // end private abstract class DoubleOrderedMapIterator // final for performance private static final class Node implements Map.Entry, KeyValue { private Comparable[] data; 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 Comparable key, final Comparable value) { data = new Comparable[]{ key, value }; leftNode = new Node[]{ null, null }; rightNode = new Node[]{ null, null }; parentNode = new Node[]{ null, null }; blackColor = new boolean[]{ true, true }; calculatedHashCode = false; } /** * get the specified data * * @param index KEY or VALUE * * @return the key or value */ private Comparable getData(final int index) { return data[index]; } /** * Set this node's left node * * @param node the new left node * @param index KEY or VALUE */ private void setLeft(final Node node, final int index) { leftNode[index] = node; } /** * get the left node * * @param index KEY or VALUE * * @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 KEY or VALUE */ private void setRight(final Node node, final int index) { rightNode[index] = node; } /** * get the right node * * @param index KEY or VALUE * * @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 KEY or VALUE */ private void setParent(final Node node, final int index) { parentNode[index] = node; } /** * get the parent node * * @param index KEY or VALUE * * @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 KEY or VALUE */ 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 KEY or VALUE * * @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 KEY or VALUE * * @return true if non-black */ private boolean isRed(final int index) { return !blackColor[index]; } /** * make this node black * * @param index KEY or VALUE */ private void setBlack(final int index) { blackColor[index] = true; } /** * make this node red * * @param index KEY or VALUE */ 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 KEY or VALUE */ private void copyColor(final Node node, final int index) { blackColor[index] = node.blackColor[index]; } /* ********** START implementation of Map.Entry ********** */ /** * @return the key corresponding to this entry. */ public Object getKey() { return data[KEY]; } /** * @return the value corresponding to this entry. */ public Object getValue() { return data[VALUE]; } /** * Optional operation that is not permitted in this * implementation * * @param ignored * * @return does not return * * @throws UnsupportedOperationException */ public Object setValue(Object 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 o object to be compared for equality with this map * entry. * @return true if the specified object is equal to this map * entry. */ public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof Map.Entry)) { return false; } Map.Entry e = (Map.Entry) o; return data[KEY].equals(e.getKey()) && data[VALUE].equals(e.getValue()); } /** * @return the hash code value for this map entry. */ public int hashCode() { if (!calculatedHashCode) { hashcodeValue = data[KEY].hashCode() ^ data[VALUE].hashCode(); calculatedHashCode = true; } return hashcodeValue; } /* ********** END implementation of Map.Entry ********** */ } } // end public class DoubleOrderedMap libcommons-collections3-java.orig/src/java/org/apache/commons/collections/EnumerationUtils.java0000644000175000017500000000367010777673522031512 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; import java.util.Enumeration; import java.util.List; import org.apache.commons.collections.iterators.EnumerationIterator; /** * Provides utility methods for {@link Enumeration} instances. * * @since Commons Collections 3.0 * @version $Id: EnumerationUtils.java 646777 2008-04-10 12:33:15Z niallp $ * * @author Gary Gregory */ 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)); } } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/ExtendedProperties.java0000644000175000017500000016265610777673522032032 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.LineNumberReader; import java.io.OutputStream; import java.io.PrintWriter; import java.io.Reader; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.Enumeration; import java.util.Hashtable; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import java.util.Properties; import java.util.StringTokenizer; import java.util.Vector; /** * 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 * as 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! * * @since Commons Collections 1.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @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 Stephen Colebourne * @author Shinobu Kawai * @author Henning P. Schmiedehausen */ 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(); String line = readLine(); while (line != null) { line = line.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); return buffer.toString(); // normal method end } } line = readLine(); } return null; // EOF reached } } /** * 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(); if (line == null) { return; // EOF } 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); } } } } 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 List values = new Vector(2); values.add(current); values.add(value); put(key, values); } else if (current instanceof List) { // already a list - just add the new token ((List) current).add(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 List) { List values = (List) value; for (Iterator it = values.iterator(); it.hasNext(); ) { String currentElement = (String) it.next(); 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 List) { return interpolate((String) ((List) 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/List. * @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/List. * @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/List. */ public String[] getStringArray(String key) { Object value = get(key); List values; if (value instanceof String) { values = new Vector(1); values.add(value); } else if (value instanceof List) { values = (List) 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/List object"); } String[] tokens = new String[values.size()]; for (int i = 0; i < tokens.length; i++) { tokens[i] = (String) values.get(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. *

      * The list is a copy of the internal data of this object, and as * such you may alter it freely. * * @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 List) { return new Vector((List) value); } else if (value instanceof String) { Vector values = new Vector(1); values.add(value); put(key, values); return values; } 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 List of strings associated with the given configuration key. *

      * The list is a copy of the internal data of this object, and as * such you may alter it freely. * * @param key The configuration key. * @return The associated List object. * @throws ClassCastException is thrown if the key maps to an * object that is not a List. * @since Commons Collections 3.2 */ public List getList(String key) { return getList(key, null); } /** * Get a List of strings associated with the given configuration key. *

      * The list is a copy of the internal data of this object, and as * such you may alter it freely. * * @param key The configuration key. * @param defaultValue The default value. * @return The associated List. * @throws ClassCastException is thrown if the key maps to an * object that is not a List. * @since Commons Collections 3.2 */ public List getList(String key, List defaultValue) { Object value = get(key); if (value instanceof List) { return new ArrayList((List) value); } else if (value instanceof String) { List values = new ArrayList(1); values.add(value); put(key, values); return values; } else if (value == null) { if (defaults != null) { return defaults.getList(key, defaultValue); } else { return ((defaultValue == null) ? new ArrayList() : defaultValue); } } else { throw new ClassCastException('\'' + key + "' doesn't map to a List 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. *

      * NOTE: From Commons Collections 3.2 this method will pick up * any default parent Properties of the specified input object. * * @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.propertyNames(); e.hasMoreElements();) { String s = (String) e.nextElement(); c.setProperty(s, props.getProperty(s)); } return c; } } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/Factory.java0000644000175000017500000000331310777673521027603 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; /** * 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. * * @since Commons Collections 2.1 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Arron Bates * @author Stephen Colebourne */ public interface Factory { /** * Create a new object. * * @return a new object * @throws FunctorException (runtime) if the factory cannot create an object */ public Object create(); } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/FactoryUtils.java0000644000175000017500000001303410777673522030626 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; import org.apache.commons.collections.functors.ConstantFactory; import org.apache.commons.collections.functors.InstantiateFactory; import org.apache.commons.collections.functors.ExceptionFactory; import org.apache.commons.collections.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. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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. * * @see org.apache.commons.collections.functors.ExceptionFactory * * @return the factory */ 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. * * @see org.apache.commons.collections.functors.ConstantFactory * * @return the factory */ 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. * * @see org.apache.commons.collections.functors.ConstantFactory * * @param constantToReturn the constant object to return each time in the factory * @return the constant factory. */ public static Factory constantFactory(Object 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 *
          * * @see org.apache.commons.collections.functors.PrototypeFactory * * @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 prototypeFactory(Object prototype) { return PrototypeFactory.getInstance(prototype); } /** * Creates a Factory that can create objects of a specific type using * a no-args constructor. * * @see org.apache.commons.collections.functors.InstantiateFactory * * @param classToInstantiate the Class to instantiate each time in the factory * @return the reflection factory * @throws IllegalArgumentException if the classToInstantiate is null */ 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. * * @see org.apache.commons.collections.functors.InstantiateFactory * * @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 */ public static Factory instantiateFactory(Class classToInstantiate, Class[] paramTypes, Object[] args) { return InstantiateFactory.getInstance(classToInstantiate, paramTypes, args); } } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/FastArrayList.java0000644000175000017500000011514010777673522030727 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; import java.util.ArrayList; import java.util.Collection; import java.util.ConcurrentModificationException; import java.util.Iterator; import java.util.List; import java.util.ListIterator; /** *

          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.

          * * @since Commons Collections 1.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Craig R. McClanahan * @author Stephen Colebourne */ 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(Object 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 * * @exception IndexOutOfBoundsException if the index is out of range */ public void add(int index, Object 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 * * @exception 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. * * @exception 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 * * @exception IndexOutOfBoundsException if the index is out of range */ public Object 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. *

          * Thread safety
          * The iterator returned is thread-safe ONLY in FAST mode. * In slow mode there is no way to synchronize, or make the iterator thread-safe. *

          * In fast mode iteration and modification may occur in parallel on different threads, * however there is a restriction. Modification must be EITHER via the Iterator * interface methods OR the List interface. If a mixture of modification * methods is used a ConcurrentModificationException is thrown from the iterator * modification method. If the List modification methods are used the changes are * NOT visible in the iterator (it shows the list contents at the time the iterator * was created). * * @return the iterator */ 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. *

          * Thread safety
          * The iterator returned is thread-safe ONLY in FAST mode. * In slow mode there is no way to synchronize, or make the iterator thread-safe. *

          * In fast mode iteration and modification may occur in parallel on different threads, * however there is a restriction. Modification must be EITHER via the Iterator * interface methods OR the List interface. If a mixture of modification * methods is used a ConcurrentModificationException is thrown from the iterator * modification method. If the List modification methods are used the changes are * NOT visible in the iterator (it shows the list contents at the time the iterator * was created). * * @return the list 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. *

          * Thread safety
          * The iterator returned is thread-safe ONLY in FAST mode. * In slow mode there is no way to synchronize, or make the iterator thread-safe. *

          * In fast mode iteration and modification may occur in parallel on different threads, * however there is a restriction. Modification must be EITHER via the Iterator * interface methods OR the List interface. If a mixture of modification * methods is used a ConcurrentModificationException is thrown from the iterator * modification method. If the List modification methods are used the changes are * NOT visible in the iterator (it shows the list contents at the time the iterator * was created). * * @param index The starting position of the iterator to return * @return the list iterator * @exception 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 * * @exception IndexOutOfBoundsException if the index is out of range */ public Object remove(int index) { if (fast) { synchronized (this) { ArrayList temp = (ArrayList) list.clone(); Object 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 * * @exception 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 * * @exception 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 * * @exception IndexOutOfBoundsException if the index is out of range */ public Object set(int index, Object 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 * * @exception 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 * * @exception ArrayStoreException if the runtime type of array * is not a supertype of the runtime type of every element in this list */ public Object[] toArray(Object 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 Object[] toArray(Object[] 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(Object 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, Object 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 Object remove(int i) { if (fast) { synchronized (FastArrayList.this) { ArrayList temp = (ArrayList) list.clone(); Object o = get(temp).remove(i); last--; list = temp; expected = temp; return o; } } else { synchronized (list) { return get(expected).remove(i); } } } public Object set(int i, Object a) { if (fast) { synchronized (FastArrayList.this) { ArrayList temp = (ArrayList) list.clone(); Object 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 Object 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 Object next() { checkMod(); lastReturnedIndex = iter.nextIndex(); return iter.next(); } public boolean hasPrevious() { checkMod(); return iter.hasPrevious(); } public Object 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(lastReturnedIndex); lastReturnedIndex = -1; } public void set(Object o) { checkMod(); if (lastReturnedIndex < 0) { throw new IllegalStateException(); } get().set(lastReturnedIndex, o); expected = list; iter = get().listIterator(previousIndex() + 1); } public void add(Object o) { checkMod(); int i = nextIndex(); get().add(i, o); last++; expected = list; 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() { return iter.hasNext(); } public Object next() { lastReturnedIndex = iter.nextIndex(); return iter.next(); } public boolean hasPrevious() { return iter.hasPrevious(); } public Object previous() { lastReturnedIndex = iter.previousIndex(); return iter.previous(); } public int previousIndex() { return iter.previousIndex(); } public int nextIndex() { return iter.nextIndex(); } public void remove() { checkMod(); if (lastReturnedIndex < 0) { throw new IllegalStateException(); } get().remove(lastReturnedIndex); expected = list; iter = get().listIterator(lastReturnedIndex); lastReturnedIndex = -1; } public void set(Object o) { checkMod(); if (lastReturnedIndex < 0) { throw new IllegalStateException(); } get().set(lastReturnedIndex, o); expected = list; iter = get().listIterator(previousIndex() + 1); } public void add(Object o) { checkMod(); int i = nextIndex(); get().add(i, o); expected = list; iter = get().listIterator(i + 1); lastReturnedIndex = -1; } } } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/FastHashMap.java0000644000175000017500000005304210777673522030340 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; import java.util.Collection; import java.util.ConcurrentModificationException; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; /** *

          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.

          * * @since Commons Collections 1.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Craig R. McClanahan * @author Stephen Colebourne */ 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 Object 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 Object put(Object key, Object value) { if (fast) { synchronized (this) { HashMap temp = (HashMap) map.clone(); Object 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 Object remove(Object key) { if (fast) { synchronized (this) { HashMap temp = (HashMap) map.clone(); Object 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 Object 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 Object 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 Object[] toArray(Object[] 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(Object 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 Object 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 Object 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 Object 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 Object iteratorNext(Map.Entry entry) { return entry; } } } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/FastTreeMap.java0000644000175000017500000006044310777673522030357 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; import java.util.Collection; import java.util.Comparator; import java.util.ConcurrentModificationException; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.SortedMap; import java.util.TreeMap; /** *

          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.

          * * @since Commons Collections 1.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Craig R. McClanahan * @author Stephen Colebourne */ 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 Object 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 Object 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 Object 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 Object put(Object key, Object value) { if (fast) { synchronized (this) { TreeMap temp = (TreeMap) map.clone(); Object 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 Object remove(Object key) { if (fast) { synchronized (this) { TreeMap temp = (TreeMap) map.clone(); Object 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 Object 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(Object 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(Object fromKey, Object 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(Object 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 Object 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 Object[] toArray(Object[] 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(Object 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 Object 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 Object 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 Object 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 Object iteratorNext(Map.Entry entry) { return entry; } } } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/FunctorException.java0000644000175000017500000001057010777673522031477 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; 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. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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); } } } } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/HashBag.java0000644000175000017500000000325510777673521027476 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; import java.util.Collection; import java.util.HashMap; /** * A {@link Bag} that is backed by a {@link HashMap}. * * @deprecated Moved to bag subpackage and rewritten internally. Due to be removed in v4.0. * @since Commons Collections 2.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Chuck Burdick */ public class HashBag extends DefaultMapBag implements Bag { /** * Constructs an empty HashBag. */ public HashBag() { super(new HashMap()); } /** * Constructs a {@link 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); } } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/IterableMap.java0000644000175000017500000000416010777673522030363 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; 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");
           * }
           * 
          * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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(); } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/IteratorUtils.java0000644000175000017500000011214110777673521031006 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; import java.lang.reflect.Array; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collection; import java.util.Comparator; import java.util.Dictionary; import java.util.Enumeration; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.Map; import org.apache.commons.collections.iterators.ArrayIterator; import org.apache.commons.collections.iterators.ArrayListIterator; import org.apache.commons.collections.iterators.CollatingIterator; import org.apache.commons.collections.iterators.EmptyIterator; import org.apache.commons.collections.iterators.EmptyListIterator; import org.apache.commons.collections.iterators.EmptyMapIterator; import org.apache.commons.collections.iterators.EmptyOrderedIterator; import org.apache.commons.collections.iterators.EmptyOrderedMapIterator; import org.apache.commons.collections.iterators.EnumerationIterator; import org.apache.commons.collections.iterators.FilterIterator; import org.apache.commons.collections.iterators.FilterListIterator; import org.apache.commons.collections.iterators.IteratorChain; import org.apache.commons.collections.iterators.IteratorEnumeration; import org.apache.commons.collections.iterators.ListIteratorWrapper; import org.apache.commons.collections.iterators.LoopingIterator; import org.apache.commons.collections.iterators.LoopingListIterator; import org.apache.commons.collections.iterators.ObjectArrayIterator; import org.apache.commons.collections.iterators.ObjectArrayListIterator; import org.apache.commons.collections.iterators.ObjectGraphIterator; import org.apache.commons.collections.iterators.SingletonIterator; import org.apache.commons.collections.iterators.SingletonListIterator; import org.apache.commons.collections.iterators.TransformIterator; import org.apache.commons.collections.iterators.UnmodifiableIterator; import org.apache.commons.collections.iterators.UnmodifiableListIterator; import org.apache.commons.collections.iterators.UnmodifiableMapIterator; /** * 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. * * @since Commons Collections 2.1 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne * @author Phil Steitz */ 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(Object 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(Object 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(Object[] 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(Object[] 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(Object[] 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(Object[] 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(Object[] 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(Object[] 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 collections 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); } /** * Gets an iterator that loops continuously over the supplied list. *

          * The iterator will only stop looping if the remove method is called * enough times to empty the list, or if the list is empty to start with. * * @param list the list to iterate over, not null * @return a new looping iterator * @throws NullPointerException if the list is null * @since Commons Collections 3.2 */ public static ResettableListIterator loopingListIterator(List list) { if (list == null) { throw new NullPointerException("List must not be null"); } return new LoopingListIterator(list); } // 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 Object[] toArray(Iterator iterator) { if (iterator == null) { throw new NullPointerException("Iterator must not be null"); } List list = toList(iterator, 100); return 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 Object[] 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((Object[]) 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", (Class[]) null); if (Iterator.class.isAssignableFrom(method.getReturnType())) { Iterator it = (Iterator) method.invoke(obj, (Object[]) null); if (it != null) { return it; } } } catch (Exception ex) { // ignore } return singletonIterator(obj); } } } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/KeyValue.java0000644000175000017500000000277210777673522027732 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; /** * 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. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ public interface KeyValue { /** * Gets the key from the pair. * * @return the key */ Object getKey(); /** * Gets the value from the pair. * * @return the value */ Object getValue(); } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/ListUtils.java0000644000175000017500000004022510777673522030134 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import org.apache.commons.collections.list.FixedSizeList; import org.apache.commons.collections.list.LazyList; import org.apache.commons.collections.list.PredicatedList; import org.apache.commons.collections.list.SynchronizedList; import org.apache.commons.collections.list.TransformedList; import org.apache.commons.collections.list.TypedList; import org.apache.commons.collections.list.UnmodifiableList; /** * Provides utility methods and decorators for {@link List} instances. * * @since Commons Collections 1.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Federico Barbieri * @author Peter Donald * @author Paul Jack * @author Stephen Colebourne * @author Neil O'Toole * @author Matthew Hawthorne */ 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 Object 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. * * @see java.util.List * @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 */ 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(); Object obj1 = null; Object 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. * * @see java.util.List#hashCode() * @param list the list to generate the hashCode for, may be null * @return the hash code */ 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 List containing all the elements in collection * that are also in retain. The cardinality of an element e * in the returned list is the same as the cardinality of e * in collection unless retain does not contain e, in which * case the cardinality is zero. This method is useful if you do not wish to modify * the collection c and thus cannot call collection.retainAll(retain);. * * @param collection the collection whose contents are the target of the #retailAll operation * @param retain the collection containing the elements to be retained in the returned collection * @return a List containing all the elements of c * that occur at least once in retain. * @throws NullPointerException if either parameter is null * @since Commons Collections 3.2 */ public static List retainAll(Collection collection, Collection retain) { List list = new ArrayList(Math.min(collection.size(), retain.size())); for (Iterator iter = collection.iterator(); iter.hasNext();) { Object obj = iter.next(); if (retain.contains(obj)) { list.add(obj); } } return list; } /** * Removes the elements in remove from collection. That is, this * method returns a list containing all the elements in c * that are not in remove. The cardinality of an element e * in the returned collection is the same as the cardinality of e * in collection unless remove contains e, in which * case the cardinality is zero. This method is useful if you do not wish to modify * collection and thus cannot call collection.removeAll(remove);. * * @param collection the collection from which items are removed (in the returned collection) * @param remove the items to be removed from the returned collection * @return a List containing all the elements of c except * any elements that also occur in remove. * @throws NullPointerException if either parameter is null * @since Commons Collections 3.2 */ public static List removeAll(Collection collection, Collection remove) { List list = new ArrayList(); for (Iterator iter = collection.iterator(); iter.hasNext();) { Object obj = iter.next(); if (remove.contains(obj) == false) { list.add(obj); } } return list; } //----------------------------------------------------------------------- /** * 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 */ 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); } } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/LRUMap.java0000644000175000017500000001612610777673521027302 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; import java.io.Externalizable; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.Iterator; /** *

          * An implementation of a Map which has a maximum size and uses a Least Recently Used * algorithm to remove items from the Map when the maximum size is reached and new items are added. *

          * *

          * A synchronized version can be obtained with: * Collections.synchronizedMap( theMapToSynchronize ) * If it will be accessed by multiple threads, you _must_ synchronize access * to this Map. Even concurrent get(Object) operations produce indeterminate * behaviour. *

          * *

          * Unlike the Collections 1.0 version, this version of LRUMap does use a true * LRU algorithm. The keys for all gets and puts are moved to the front of * the list. LRUMap is now a subclass of SequencedHashMap, and the "LRU" * key is now equivalent to LRUMap.getFirst(). *

          * * @deprecated Moved to map subpackage. Due to be removed in v4.0. * @since Commons Collections 1.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author James Strachan * @author Morgan Delagrange */ public class LRUMap extends SequencedHashMap implements Externalizable { private int maximumSize = 0; /** * Default constructor, primarily for the purpose of * de-externalization. This constructors sets a default * LRU limit of 100 keys, but this value may be overridden * internally as a result of de-externalization. */ public LRUMap() { this( 100 ); } /** * Create a new LRUMap with a maximum capacity of i. * Once i capacity is achieved, subsequent gets * and puts will push keys out of the map. See . * * @param i Maximum capacity of the LRUMap */ public LRUMap(int i) { super( i ); maximumSize = i; } /** *

          Get the value for a key from the Map. The key * will be promoted to the Most Recently Used position. * Note that get(Object) operations will modify * the underlying Collection. Calling get(Object) * inside of an iteration over keys, values, etc. is * currently unsupported.

          * * @param key Key to retrieve * @return Returns the value. Returns null if the key has a * null value or if the key has no value. */ public Object get(Object key) { if(!containsKey(key)) return null; Object value = remove(key); super.put(key,value); return value; } /** *

          Removes the key and its Object from the Map.

          * *

          (Note: this may result in the "Least Recently Used" * object being removed from the Map. In that case, * the removeLRU() method is called. See javadoc for * removeLRU() for more details.)

          * * @param key Key of the Object to add. * @param value Object to add * @return Former value of the key */ public Object put( Object key, Object value ) { int mapSize = size(); Object retval = null; if ( mapSize >= maximumSize ) { // don't retire LRU if you are just // updating an existing key if (!containsKey(key)) { // lets retire the least recently used item in the cache removeLRU(); } } retval = super.put(key,value); return retval; } /** * This method is used internally by the class for * finding and removing the LRU Object. */ protected void removeLRU() { Object key = getFirstKey(); // be sure to call super.get(key), or you're likely to // get infinite promotion recursion Object value = super.get(key); remove(key); processRemovedLRU(key,value); } /** * Subclasses of LRUMap may hook into this method to * provide specialized actions whenever an Object is * automatically removed from the cache. By default, * this method does nothing. * * @param key key that was removed * @param value value of that key (can be null) */ protected void processRemovedLRU(Object key, Object value) { } // Externalizable interface //------------------------------------------------------------------------- public void readExternal( ObjectInput in ) throws IOException, ClassNotFoundException { maximumSize = in.readInt(); int size = in.readInt(); for( int i = 0; i < size; i++ ) { Object key = in.readObject(); Object value = in.readObject(); put(key,value); } } public void writeExternal( ObjectOutput out ) throws IOException { out.writeInt( maximumSize ); out.writeInt( size() ); for( Iterator iterator = keySet().iterator(); iterator.hasNext(); ) { Object key = iterator.next(); out.writeObject( key ); // be sure to call super.get(key), or you're likely to // get infinite promotion recursion Object value = super.get( key ); out.writeObject( value ); } } // Properties //------------------------------------------------------------------------- /** Getter for property maximumSize. * @return Value of property maximumSize. */ public int getMaximumSize() { return maximumSize; } /** Setter for property maximumSize. * @param maximumSize New value of property maximumSize. */ public void setMaximumSize(int maximumSize) { this.maximumSize = maximumSize; while (size() > maximumSize) { removeLRU(); } } // add a serial version uid, so that if we change things in the future // without changing the format, we can still deserialize properly. private static final long serialVersionUID = 2197433140769957051L; } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/MapIterator.java0000644000175000017500000001016510777673521030426 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; 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);
           * }
           * 
          * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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 */ Object 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 */ Object 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 */ Object 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() */ Object setValue(Object value); } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/MapUtils.java0000644000175000017500000017744410777673522027754 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; import java.io.PrintStream; import java.text.NumberFormat; import java.text.ParseException; import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Properties; import java.util.ResourceBundle; import java.util.SortedMap; import java.util.TreeMap; import org.apache.commons.collections.map.FixedSizeMap; import org.apache.commons.collections.map.FixedSizeSortedMap; import org.apache.commons.collections.map.LazyMap; import org.apache.commons.collections.map.LazySortedMap; import org.apache.commons.collections.map.ListOrderedMap; import org.apache.commons.collections.map.MultiValueMap; import org.apache.commons.collections.map.PredicatedMap; import org.apache.commons.collections.map.PredicatedSortedMap; import org.apache.commons.collections.map.TransformedMap; import org.apache.commons.collections.map.TransformedSortedMap; import org.apache.commons.collections.map.TypedMap; import org.apache.commons.collections.map.TypedSortedMap; import org.apache.commons.collections.map.UnmodifiableMap; import org.apache.commons.collections.map.UnmodifiableSortedMap; /** * 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 #lazyMap(Map,Transformer)} *
          • {@link #lazySortedMap(SortedMap,Factory)} *
          • {@link #lazySortedMap(SortedMap,Transformer)} *
          • {@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)} *
          • {@link #multiValueMap( Map )} *
          • {@link #multiValueMap( Map, Class )} *
          • {@link #multiValueMap( Map, Factory )} *
          * * @since Commons Collections 1.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @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 Ashwin S * @author James Carman * @author Neil O'Toole */ 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 Object getObject(final Map map, final Object 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 Object key) { if (map != null) { Object 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 Object key) { if (map != null) { Object answer = map.get(key); if (answer != null && answer instanceof Map) { return (Map) 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 Object getObject( Map map, Object key, Object defaultValue ) { if ( map != null ) { Object 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, Object 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 = (String) 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 = (Map.Entry) it.next(); out.put(entry.getValue(), entry.getKey()); } return out; } //----------------------------------------------------------------------- /** * Protects against adding null values to a map. *

          * This method checks the value being added to the map, and if it is null * it is replaced by an empty string. *

          * This could be useful if the map does not accept null values, or for * receiving data from a source that may provide null or empty string * which should be held in the same way in the map. *

          * Keys are not validated. * * @param map the map to add to, may not be null * @param key the key * @param value the value, null converted to "" * @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); } } //----------------------------------------------------------------------- /** * Puts all the keys and values from the specified array into the map. *

          * This method is an alternative to the {@link java.util.Map#putAll(java.util.Map)} * method and constructors. It allows you to build a map from an object array * of various possible styles. *

          * If the first entry in the object array implements {@link java.util.Map.Entry} * or {@link KeyValue} then the key and value are added from that object. * If the first entry in the object array is an object array itself, then * it is assumed that index 0 in the sub-array is the key and index 1 is the value. * Otherwise, the array is treated as keys and values in alternate indices. *

          * For example, to create a color map: *

               * Map colorMap = MapUtils.putAll(new HashMap(), new String[][] {
               *     {"RED", "#FF0000"},
               *     {"GREEN", "#00FF00"},
               *     {"BLUE", "#0000FF"}
               * });
               * 
          * or: *
               * Map colorMap = MapUtils.putAll(new HashMap(), new String[] {
               *     "RED", "#FF0000",
               *     "GREEN", "#00FF00",
               *     "BLUE", "#0000FF"
               * });
               * 
          * or: *
               * Map colorMap = MapUtils.putAll(new HashMap(), new Map.Entry[] {
               *     new DefaultMapEntry("RED", "#FF0000"),
               *     new DefaultMapEntry("GREEN", "#00FF00"),
               *     new DefaultMapEntry("BLUE", "#0000FF")
               * });
               * 
          * * @param map the map to populate, must not be null * @param array an array to populate from, null ignored * @return the input map * @throws NullPointerException if map is null * @throws IllegalArgumentException if sub-array or entry matching used and an * entry is invalid * @throws ClassCastException if the array contents is mixed * @since Commons Collections 3.2 */ public static Map putAll(Map map, Object[] array) { map.size(); // force NPE if (array == null || array.length == 0) { return map; } Object obj = array[0]; if (obj instanceof Map.Entry) { for (int i = 0; i < array.length; i++) { Map.Entry entry = (Map.Entry) array[i]; map.put(entry.getKey(), entry.getValue()); } } else if (obj instanceof KeyValue) { for (int i = 0; i < array.length; i++) { KeyValue keyval = (KeyValue) array[i]; map.put(keyval.getKey(), keyval.getValue()); } } else if (obj instanceof Object[]) { for (int i = 0; i < array.length; i++) { Object[] sub = (Object[]) array[i]; if (sub == null || sub.length < 2) { throw new IllegalArgumentException("Invalid array element: " + i); } map.put(sub[0], sub[1]); } } else { for (int i = 0; i < array.length - 1;) { map.put(array[i++], array[i++]); } } return map; } //----------------------------------------------------------------------- /** * Null-safe check if the specified map is empty. *

          * Null returns true. * * @param map the map to check, may be null * @return true if empty or null * @since Commons Collections 3.2 */ public static boolean isEmpty(Map map) { return (map == null || map.isEmpty()); } /** * Null-safe check if the specified map is not empty. *

          * Null returns false. * * @param map the map to check, may be null * @return true if non-null and non-empty * @since Commons Collections 3.2 */ public static boolean isNotEmpty(Map map) { return !MapUtils.isEmpty(map); } // 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 */ 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. *

          * This method returns a new map (decorating the specified map) that * will transform any new entries added to it. * Existing entries in the specified map will not be transformed. * If you want that behaviour, see {@link TransformedMap#decorateTransform}. *

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

          * If there are any elements already in the map being decorated, they * are NOT transformed. * * @param map the map to transform, must not be null, typically empty * @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 "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. The factory is a {@link Transformer} * that will be passed the key which it must transform into the value. *

          * For instance: *

               * Transformer factory = new Transformer() {
               *     public Object transform(Object mapKey) {
               *         return new File(mapKey);
               *     }
               * }
               * Map lazyMap = MapUtils.lazyMap(new HashMap(), factory);
               * Object obj = lazyMap.get("C:/dev");
               * 
          * * After the above code is executed, obj will contain * a new File instance for the C drive dev directory. * Furthermore, that File instance is the value for the * "C:/dev" key in the map. *

          * If a lazy map is wrapped by a synchronized map, the result is a simple * synchronized cache. When an object is not is the cache, the cache itself * calls back to the factory Transformer to populate itself, all within the * same synchronized block. * * @param map the map to make lazy, must not be null * @param transformerFactory 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 Transformer is null */ public static Map lazyMap(Map map, Transformer transformerFactory) { return LazyMap.decorate(map, transformerFactory); } /** * 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); } /** * Creates a mult-value map backed by the given map which returns * collections of type ArrayList. * * @param map the map to decorate * @return a multi-value map backed by the given map which returns ArrayLists of values. * @see MultiValueMap * @since Commons Collections 3.2 */ public static Map multiValueMap(Map map) { return MultiValueMap.decorate(map); } /** * Creates a multi-value map backed by the given map which returns * collections of the specified type. * * @param map the map to decorate * @param collectionClass the type of collections to return from the map (must contain public no-arg constructor * and extend Collection). * @return a multi-value map backed by the given map which returns collections of the specified type * @see MultiValueMap * @since Commons Collections 3.2 */ public static Map multiValueMap(Map map, Class collectionClass) { return MultiValueMap.decorate(map, collectionClass); } /** * Creates a multi-value map backed by the given map which returns * collections created by the specified collection factory. * * @param map the map to decorate * @param collectionFactory a factor which creates collection objects * @return a multi-value map backed by the given map which returns collections * created by the specified collection factory * @see MultiValueMap * @since Commons Collections 3.2 */ public static Map multiValueMap(Map map, Factory collectionFactory) { return MultiValueMap.decorate(map, collectionFactory); } // 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 */ 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. *

          * This method returns a new sorted map (decorating the specified map) that * will transform any new entries added to it. * Existing entries in the specified map will not be transformed. * If you want that behaviour, see {@link TransformedSortedMap#decorateTransform}. *

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

          * If there are any elements already in the map being decorated, they * are NOT transformed. * * @param map the map to transform, must not be null, typically empty * @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); } /** * 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. The factory is a {@link Transformer} * that will be passed the key which it must transform into the value. *

          * For instance: *

               * Transformer factory = new Transformer() {
               *     public Object transform(Object mapKey) {
               *         return new File(mapKey);
               *     }
               * }
               * SortedMap lazy = MapUtils.lazySortedMap(new TreeMap(), factory);
               * Object obj = lazy.get("C:/dev");
               * 
          * * After the above code is executed, obj will contain * a new File instance for the C drive dev directory. * Furthermore, that File instance is the value for the * "C:/dev" key in the map. *

          * If a lazy map is wrapped by a synchronized map, the result is a simple * synchronized cache. When an object is not is the cache, the cache itself * calls back to the factory Transformer to populate itself, all within the * same synchronized block. * * @param map the map to make lazy, must not be null * @param transformerFactory 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 Transformer is null */ public static SortedMap lazySortedMap(SortedMap map, Transformer transformerFactory) { return LazySortedMap.decorate(map, transformerFactory); } } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/MultiHashMap.java0000644000175000017500000004020710777673522030534 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; import java.io.IOException; import java.io.ObjectInputStream; import java.util.AbstractCollection; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; import org.apache.commons.collections.iterators.EmptyIterator; /** * MultiHashMap is the default implementation of the * {@link org.apache.commons.collections.MultiMap MultiMap} interface. *

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

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

           * MultiMap mhm = new MultiHashMap();
           * mhm.put(key, "A");
           * mhm.put(key, "B");
           * mhm.put(key, "C");
           * List list = (List) mhm.get(key);
          *

          * list will be a list containing "A", "B", "C". * * @deprecated Class now available as MultiValueMap in map subpackage. * This version is due to be removed in collections v4.0. * * @since Commons Collections 2.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Christopher Berry * @author James Strachan * @author Steve Downey * @author Stephen Colebourne * @author Julien Buret * @author Serhiy Yevtushenko * @author Robert Ribnitz */ public class MultiHashMap extends HashMap implements MultiMap { // backed values collection private transient Collection values = null; // compatibility with commons-collection releases 2.0/2.1 private static final long serialVersionUID = 1943563828307035349L; /** * Constructor. */ public MultiHashMap() { super(); } /** * Constructor. * * @param initialCapacity the initial map capacity */ public MultiHashMap(int initialCapacity) { super(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) { super(initialCapacity, loadFactor); } /** * Constructor that copies the input map creating an independent copy. *

          * This method performs different behaviour depending on whether the map * specified is a MultiMap or not. If a MultiMap is specified, each internal * collection is also cloned. If the specified map only implements Map, then * the values are not cloned. *

          * NOTE: From Commons Collections 3.1 this method correctly copies a MultiMap * to form a truly independent new map. * NOTE: From Commons Collections 3.2 this method delegates to the newly * added putAll(Map) override method. * * @param mapToCopy a Map to copy */ public MultiHashMap(Map mapToCopy) { // be careful of JDK 1.3 vs 1.4 differences super((int) (mapToCopy.size() * 1.4f)); putAll(mapToCopy); } /** * 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 = (Map.Entry) iterator.next(); // put has created a extra collection level, remove it super.put(entry.getKey(), ((Collection) entry.getValue()).iterator().next()); } } } //----------------------------------------------------------------------- /** * 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 = super.values(); for (Iterator it = values.iterator(); it.hasNext();) { Collection coll = (Collection) 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 (Collection) 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 Object put(Object key, Object 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); super.put(key, coll); } boolean results = coll.add(value); return (results ? value : null); } /** * Override superclass to ensure that MultiMap instances are * correctly handled. *

          * NOTE: Prior to version 3.2, putAll(map) did not work properly * when passed a MultiMap. * * @param map the map to copy (either a normal or multi map) */ public void putAll(Map map) { if (map instanceof MultiMap) { for (Iterator it = map.entrySet().iterator(); it.hasNext();) { Map.Entry entry = (Map.Entry) it.next(); Collection coll = (Collection) entry.getValue(); putAll(entry.getKey(), coll); } } else { for (Iterator it = map.entrySet().iterator(); it.hasNext();) { Map.Entry entry = (Map.Entry) it.next(); put(entry.getKey(), entry.getValue()); } } } /** * 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(Object 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; } super.put(key, coll); return true; } else { return coll.addAll(values); } } /** * Checks whether the map contains the value specified. *

          * This checks all collections 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 = super.entrySet(); if (pairs == null) { return false; } Iterator pairsIterator = pairs.iterator(); while (pairsIterator.hasNext()) { Map.Entry keyValuePair = (Map.Entry) pairsIterator.next(); Collection coll = (Collection) 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 Object remove(Object key, Object item) { Collection valuesForKey = getCollection(key); if (valuesForKey == null) { return null; } boolean removed = valuesForKey.remove(item); if (removed == false) { return null; } // remove the list if it is now empty // (saves space, and allows equals to work) if (valuesForKey.isEmpty()){ remove(key); } return 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 = super.entrySet(); Iterator pairsIterator = pairs.iterator(); while (pairsIterator.hasNext()) { Map.Entry keyValuePair = (Map.Entry) pairsIterator.next(); Collection coll = (Collection) keyValuePair.getValue(); coll.clear(); } super.clear(); } /** * 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())); } /** * Gets the values iterator from the superclass, as used by inner class. * * @return iterator */ Iterator superValuesIterator() { return super.values().iterator(); } //----------------------------------------------------------------------- /** * 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 = MultiHashMap.this.superValuesIterator(); } private boolean searchNextIterator() { while (tempIterator == null || tempIterator.hasNext() == false) { if (backedIterator.hasNext() == false) { return false; } tempIterator = ((Collection) backedIterator.next()).iterator(); } return true; } public boolean hasNext() { return searchNextIterator(); } public Object 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 collections as well as the map. * * @return the cloned map */ public Object clone() { MultiHashMap cloned = (MultiHashMap) super.clone(); // clone each Collection container for (Iterator it = cloned.entrySet().iterator(); it.hasNext();) { Map.Entry entry = (Map.Entry) it.next(); Collection coll = (Collection) entry.getValue(); Collection newColl = createCollection(coll); entry.setValue(newColl); } return cloned; } /** * 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); } } } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/MultiMap.java0000644000175000017500000001555610777673522027741 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; import java.util.Collection; import java.util.Map; /** * 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: *

           * MultiMap mhm = new MultiHashMap();
           * mhm.put(key, "A");
           * mhm.put(key, "B");
           * mhm.put(key, "C");
           * Collection coll = (Collection) mhm.get(key);
          *

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

          * NOTE: Additional methods were added to this interface in Commons Collections 3.1. * These were added solely for documentation purposes and do not change the interface * as they were defined in the superinterface Map anyway. * * @since Commons Collections 2.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Christopher Berry * @author James Strachan * @author Stephen Colebourne */ public interface MultiMap extends Map { /** * 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 Object remove(Object key, Object item); //----------------------------------------------------------------------- /** * Gets the number of keys in this map. *

          * Implementations typically return only the count of keys in the map * This cannot be mandated due to backwards compatability of this interface. * * @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 typically return null if no values have * been mapped to the key, however the implementation may choose to * return an empty collection. *

          * 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 */ Object get(Object key); /** * Checks whether the map contains the value specified. *

          * Implementations typically check all collections against all keys for the value. * This cannot be mandated due to backwards compatability of this interface. * * @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); /** * 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 */ Object put(Object key, Object value); /** * Removes all values associated with the specified key. *

          * Implementations typically return null from a subsequant * 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 */ Object remove(Object key); /** * Gets a collection containing all the values in the map. *

          * Inplementations typically return a collection containing the combination * of values from all keys. * This cannot be mandated due to backwards compatability of this interface. * * @return a collection view of the values contained in this map */ Collection values(); } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/OrderedBidiMap.java0000644000175000017500000000524210777673521031011 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; /** * 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. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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(); } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/OrderedIterator.java0000644000175000017500000000331210777673522031272 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; import java.util.Iterator; /** * Defines an iterator that operates over an ordered collection. *

          * This iterator allows both forward and reverse iteration through the collection. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ public interface OrderedIterator extends Iterator { /** * Checks to see if there is a previous element 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 element in the iteration * @throws java.util.NoSuchElementException if the iteration is finished */ Object previous(); } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/OrderedMap.java0000644000175000017500000000530410777673521030220 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; /** * Defines a map that maintains order and allows both forward and backward * iteration through that order. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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 Object 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 Object 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 Object nextKey(Object 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 Object previousKey(Object key); } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/OrderedMapIterator.java0000644000175000017500000000331310777673522031731 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; /** * Defines an iterator that operates over an ordered Map. *

          * This iterator allows both forward and reverse iteration through the map. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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 */ Object previous(); } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/overview.html0000644000175000017500000000776110777673522030101 0ustar godgod

          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.

          libcommons-collections3-java.orig/src/java/org/apache/commons/collections/package.html0000644000175000017500000000237410777673521027620 0ustar godgod

          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
          • ExtendedProperties - extends the Properties class to add extra functionality

          libcommons-collections3-java.orig/src/java/org/apache/commons/collections/Predicate.java0000644000175000017500000000407410777673521030101 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; /** * 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. * * @since Commons Collections 1.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author James Strachan * @author Stephen Colebourne */ 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(Object object); } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/PredicateUtils.java0000644000175000017500000005370410777673521031126 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; import java.util.Collection; import org.apache.commons.collections.functors.AllPredicate; import org.apache.commons.collections.functors.AndPredicate; import org.apache.commons.collections.functors.AnyPredicate; import org.apache.commons.collections.functors.EqualPredicate; import org.apache.commons.collections.functors.ExceptionPredicate; import org.apache.commons.collections.functors.FalsePredicate; import org.apache.commons.collections.functors.IdentityPredicate; import org.apache.commons.collections.functors.InstanceofPredicate; import org.apache.commons.collections.functors.InvokerTransformer; import org.apache.commons.collections.functors.NonePredicate; import org.apache.commons.collections.functors.NotNullPredicate; import org.apache.commons.collections.functors.NotPredicate; import org.apache.commons.collections.functors.NullIsExceptionPredicate; import org.apache.commons.collections.functors.NullIsFalsePredicate; import org.apache.commons.collections.functors.NullIsTruePredicate; import org.apache.commons.collections.functors.NullPredicate; import org.apache.commons.collections.functors.OnePredicate; import org.apache.commons.collections.functors.OrPredicate; import org.apache.commons.collections.functors.TransformedPredicate; import org.apache.commons.collections.functors.TransformerPredicate; import org.apache.commons.collections.functors.TruePredicate; import org.apache.commons.collections.functors.UniquePredicate; /** * 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. * * @since Commons Collections 3.0 * @version $Revision: 647116 $ $Date: 2008-04-11 12:23:08 +0100 (Fri, 11 Apr 2008) $ * * @author Stephen Colebourne * @author Ola Berg */ 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. * * @see org.apache.commons.collections.functors.ExceptionPredicate * * @return the predicate */ public static Predicate exceptionPredicate() { return ExceptionPredicate.INSTANCE; } /** * Gets a Predicate that always returns true. * * @see org.apache.commons.collections.functors.TruePredicate * * @return the predicate */ public static Predicate truePredicate() { return TruePredicate.INSTANCE; } /** * Gets a Predicate that always returns false. * * @see org.apache.commons.collections.functors.FalsePredicate * * @return the predicate */ public static Predicate falsePredicate() { return FalsePredicate.INSTANCE; } /** * Gets a Predicate that checks if the input object passed in is null. * * @see org.apache.commons.collections.functors.NullPredicate * * @return the predicate */ public static Predicate nullPredicate() { return NullPredicate.INSTANCE; } /** * Gets a Predicate that checks if the input object passed in is not null. * * @see org.apache.commons.collections.functors.NotNullPredicate * * @return the predicate */ public static Predicate notNullPredicate() { return NotNullPredicate.INSTANCE; } /** * Creates a Predicate that checks if the input object is equal to the * specified object using equals(). * * @see org.apache.commons.collections.functors.EqualPredicate * * @param value the value to compare against * @return the predicate */ public static Predicate equalPredicate(Object value) { return EqualPredicate.getInstance(value); } /** * Creates a Predicate that checks if the input object is equal to the * specified object by identity. * * @see org.apache.commons.collections.functors.IdentityPredicate * * @param value the value to compare against * @return the predicate */ public static Predicate identityPredicate(Object 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. * * @see org.apache.commons.collections.functors.InstanceofPredicate * * @param type the type to check for, may not be null * @return the predicate * @throws IllegalArgumentException if the class is null */ 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. * * @see org.apache.commons.collections.functors.UniquePredicate * * @return the predicate */ 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. * * @see org.apache.commons.collections.functors.InvokerTransformer * @see org.apache.commons.collections.functors.TransformerPredicate * * @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. */ 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. * * @see org.apache.commons.collections.functors.InvokerTransformer * @see org.apache.commons.collections.functors.TransformerPredicate * * @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 */ 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. * * @see org.apache.commons.collections.functors.AndPredicate * * @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 */ 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. * If the array of predicates is empty, then this predicate returns true. * * @see org.apache.commons.collections.functors.AllPredicate * * @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 any predicate in the array is null */ 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. * If the collection of predicates is empty, then this predicate returns true. * * @see org.apache.commons.collections.functors.AllPredicate * * @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 any predicate in the collection is null */ 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. * * @see org.apache.commons.collections.functors.OrPredicate * * @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 */ 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. * If the array of predicates is empty, then this predicate returns false. * * @see org.apache.commons.collections.functors.AnyPredicate * * @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 any predicate in the array is null */ 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. * If the collection of predicates is empty, then this predicate returns false. * * @see org.apache.commons.collections.functors.AnyPredicate * * @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 any predicate in the collection is null */ 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. * * @see org.apache.commons.collections.functors.OnePredicate * * @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 */ 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. * If the array of predicates is empty, then this predicate returns false. * * @see org.apache.commons.collections.functors.OnePredicate * * @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 any predicate in the array is null */ 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. * If the collection of predicates is empty, then this predicate returns false. * * @see org.apache.commons.collections.functors.OnePredicate * * @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 any predicate in the collection is null */ 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. * * @see org.apache.commons.collections.functors.NonePredicate * * @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 */ 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. * If the array of predicates is empty, then this predicate returns true. * * @see org.apache.commons.collections.functors.NonePredicate * * @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 any predicate in the array is null */ 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. * If the collection of predicates is empty, then this predicate returns true. * * @see org.apache.commons.collections.functors.NonePredicate * * @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 any predicate in the collection is null */ 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. * * @see org.apache.commons.collections.functors.NotPredicate * * @param predicate the predicate to not * @return the not predicate * @throws IllegalArgumentException if the predicate is null */ 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. * * @see org.apache.commons.collections.functors.TransformerPredicate * * @param transformer the transformer to wrap, may not be null * @return the transformer wrapping predicate * @throws IllegalArgumentException if the transformer is null */ 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. * * @see org.apache.commons.collections.functors.NullIsExceptionPredicate * * @param predicate the predicate to wrap, may not be null * @return the predicate * @throws IllegalArgumentException if the predicate is null. */ 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. * * @see org.apache.commons.collections.functors.NullIsFalsePredicate * * @param predicate the predicate to wrap, may not be null * @return the predicate * @throws IllegalArgumentException if the predicate is null. */ 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. * * @see org.apache.commons.collections.functors.NullIsTruePredicate * * @param predicate the predicate to wrap, may not be null * @return the predicate * @throws IllegalArgumentException if the predicate is null. */ 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. * * @see org.apache.commons.collections.functors.TransformedPredicate * * @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 * @since Commons Collections 3.1 */ public static Predicate transformedPredicate(Transformer transformer, Predicate predicate) { return TransformedPredicate.getInstance(transformer, predicate); } } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/PriorityQueue.java0000644000175000017500000000453010777673522031025 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; /** * Defines a collection for priority queues, which can insert, peek and pop. *

          * This interface is now replaced by the Buffer interface. * * @deprecated Replaced by the Buffer interface and implementations in buffer subpackage. * Due to be removed in v4.0. * @since Commons Collections 1.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Peter Donald */ public interface PriorityQueue { /** * Clear all elements from queue. */ void clear(); /** * Test if queue is empty. * * @return true if queue is empty else false. */ boolean isEmpty(); /** * Insert an element into queue. * * @param element the element to be inserted * * @throws ClassCastException if the specified element's * type prevents it from being compared to other items in the queue to * determine its relative priority. */ void insert(Object element); /** * Return element on top of heap but don't remove it. * * @return the element at top of heap * @throws java.util.NoSuchElementException if isEmpty() == true */ Object peek(); /** * Return element on top of heap and remove it. * * @return the element at top of heap * @throws java.util.NoSuchElementException if isEmpty() == true */ Object pop(); } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/ProxyMap.java0000644000175000017500000001130110777673522027750 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; import java.util.Collection; import java.util.Map; import java.util.Set; /** *

          This Map wraps another Map * implementation, using the wrapped instance for its default * implementation. This class is used as a framework on which to * build to extensions for its wrapped Map object which * would be unavailable or inconvenient via sub-classing (but usable * via composition).

          * *

          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.

          * * @deprecated Moved to map subpackage as AbstractMapDecorator. It will be removed in v4.0. * @since Commons Collections 2.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Daniel Rall * @author Stephen Colebourne */ public abstract class ProxyMap implements Map { /** * The Map to delegate to. */ protected Map map; /** * Constructor that uses the specified map to delegate to. *

          * Note that the map is used for delegation, and is not copied. This is * different to the normal use of a Map parameter in * collections constructors. * * @param map the Map to delegate to */ public ProxyMap(Map map) { this.map = map; } /** * Invokes the underlying {@link Map#clear()} method. */ public void clear() { map.clear(); } /** * Invokes the underlying {@link Map#containsKey(Object)} method. */ public boolean containsKey(Object key) { return map.containsKey(key); } /** * Invokes the underlying {@link Map#containsValue(Object)} method. */ public boolean containsValue(Object value) { return map.containsValue(value); } /** * Invokes the underlying {@link Map#entrySet()} method. */ public Set entrySet() { return map.entrySet(); } /** * Invokes the underlying {@link Map#equals(Object)} method. */ public boolean equals(Object m) { return map.equals(m); } /** * Invokes the underlying {@link Map#get(Object)} method. */ public Object get(Object key) { return map.get(key); } /** * Invokes the underlying {@link Map#hashCode()} method. */ public int hashCode() { return map.hashCode(); } /** * Invokes the underlying {@link Map#isEmpty()} method. */ public boolean isEmpty() { return map.isEmpty(); } /** * Invokes the underlying {@link Map#keySet()} method. */ public Set keySet() { return map.keySet(); } /** * Invokes the underlying {@link Map#put(Object,Object)} method. */ public Object put(Object key, Object value) { return map.put(key, value); } /** * Invokes the underlying {@link Map#putAll(Map)} method. */ public void putAll(Map t) { map.putAll(t); } /** * Invokes the underlying {@link Map#remove(Object)} method. */ public Object remove(Object key) { return map.remove(key); } /** * Invokes the underlying {@link Map#size()} method. */ public int size() { return map.size(); } /** * Invokes the underlying {@link Map#values()} method. */ public Collection values() { return map.values(); } } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/ReferenceMap.java0000644000175000017500000007043210777673521030536 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; 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.AbstractCollection; import java.util.AbstractMap; import java.util.AbstractSet; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.ConcurrentModificationException; import java.util.Iterator; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; import org.apache.commons.collections.keyvalue.DefaultMapEntry; /** * Hash-based {@link 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 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.

          * * The algorithms used are basically the same as those * in {@link java.util.HashMap}. In particular, you * can specify a load factor and capacity to suit your * needs. All optional {@link Map} operations are * supported.

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

          * * As usual, this implementation is not synchronized. You * can use {@link java.util.Collections#synchronizedMap} to * provide synchronized access to a ReferenceMap. * * @see java.lang.ref.Reference * * @deprecated Moved to map subpackage. Due to be removed in v4.0. * @since Commons Collections 2.1 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Paul Jack */ public class ReferenceMap extends AbstractMap { /** * For serialization. */ private static final long serialVersionUID = -3370601314380922368L; /** * Constant indicating that hard references should be used. */ final public static int HARD = 0; /** * Constant indicating that soft references should be used. */ final public static int SOFT = 1; /** * Constant indicating that weak references should be used. */ final public static int WEAK = 2; // --- serialized instance variables: /** * The reference type for keys. Must be HARD, SOFT, WEAK. * Note: I originally marked this field as final, but then this class * didn't compile under JDK1.2.2. * @serial */ private int keyType; /** * The reference type for values. Must be HARD, SOFT, WEAK. * Note: I originally marked this field as final, but then this class * didn't compile under JDK1.2.2. * @serial */ private int valueType; /** * The threshold variable is calculated by multiplying * table.length and loadFactor. * Note: I originally marked this field as final, but then this class * didn't compile under JDK1.2.2. * @serial */ private float loadFactor; /** * Should the value be automatically purged when the associated key has been collected? */ private boolean purgeValues = false; // -- Non-serialized instance variables /** * ReferenceQueue used to eliminate stale mappings. * See purge. */ private transient ReferenceQueue queue = new ReferenceQueue(); /** * The hash table. Its length is always a power of two. */ private transient Entry[] table; /** * Number of mappings in this map. */ private transient int size; /** * When size reaches threshold, the map is resized. * See resize(). */ private transient int threshold; /** * Number of times this map has been modified. */ private transient volatile int modCount; /** * Cached key set. May be null if key set is never accessed. */ private transient Set keySet; /** * Cached entry set. May be null if entry set is never accessed. */ private transient Set entrySet; /** * Cached values. May be null if values() is never accessed. */ private transient Collection values; /** * Constructs a new ReferenceMap that will * use hard references to keys and soft references to values. */ public ReferenceMap() { this(HARD, SOFT); } /** * 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) { this(keyType, valueType); this.purgeValues = purgeValues; } /** * 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) { this(keyType, valueType, 16, 0.75f); } /** * 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) { this(keyType, valueType, capacity, loadFactor); this.purgeValues = 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(); verify("keyType", keyType); verify("valueType", valueType); if (capacity <= 0) { throw new IllegalArgumentException("capacity must be positive"); } if ((loadFactor <= 0.0f) || (loadFactor >= 1.0f)) { throw new IllegalArgumentException("Load factor must be greater than 0 and less than 1."); } this.keyType = keyType; this.valueType = valueType; int v = 1; while (v < capacity) v *= 2; this.table = new Entry[v]; this.loadFactor = loadFactor; this.threshold = (int)(v * loadFactor); } // used by constructor private static void verify(String name, int type) { if ((type < HARD) || (type > WEAK)) { throw new IllegalArgumentException(name + " must be HARD, SOFT, WEAK."); } } /** * Writes this object to the given output stream. * * @param out the output stream to write to * @throws IOException if the stream raises it */ private void writeObject(ObjectOutputStream out) throws IOException { out.defaultWriteObject(); out.writeInt(table.length); // Have to use null-terminated list because size might shrink // during iteration for (Iterator iter = entrySet().iterator(); iter.hasNext();) { Map.Entry entry = (Map.Entry)iter.next(); out.writeObject(entry.getKey()); out.writeObject(entry.getValue()); } out.writeObject(null); } /** * Reads the contents of this object from the given input stream. * * @param inp the input stream to read from * @throws IOException if the stream raises it * @throws ClassNotFoundException if the stream raises it */ private void readObject(ObjectInputStream inp) throws IOException, ClassNotFoundException { inp.defaultReadObject(); table = new Entry[inp.readInt()]; threshold = (int)(table.length * loadFactor); queue = new ReferenceQueue(); Object key = inp.readObject(); while (key != null) { Object value = inp.readObject(); put(key, value); key = inp.readObject(); } } /** * 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 */ private Object toReference(int type, Object referent, int hash) { switch (type) { case HARD: return referent; case SOFT: return new SoftRef(hash, referent, queue); case WEAK: return new WeakRef(hash, referent, queue); default: throw new Error(); } } /** * Returns the entry associated with the given key. * * @param key the key of the entry to look up * @return the entry associated with that key, or null * if the key is not in this map */ private Entry getEntry(Object key) { if (key == null) return null; int hash = key.hashCode(); int index = indexFor(hash); for (Entry entry = table[index]; entry != null; entry = entry.next) { if ((entry.hash == hash) && key.equals(entry.getKey())) { return entry; } } return null; } /** * Converts the given hash code into an index into the * hash table. */ private int indexFor(int hash) { // mix the bits to avoid bucket collisions... hash += ~(hash << 15); hash ^= (hash >>> 10); hash += (hash << 3); hash ^= (hash >>> 6); hash += ~(hash << 11); hash ^= (hash >>> 16); return hash & (table.length - 1); } /** * Resizes this hash table by doubling its capacity. * This is an expensive operation, as entries must * be copied from the old smaller table to the new * bigger table. */ private void resize() { Entry[] old = table; table = new Entry[old.length * 2]; for (int i = 0; i < old.length; i++) { Entry next = old[i]; while (next != null) { Entry entry = next; next = next.next; int index = indexFor(entry.hash); entry.next = table[index]; table[index] = entry; } old[i] = null; } threshold = (int)(table.length * loadFactor); } /** * Purges stale mappings from this map. *

          * Ordinarily, stale mappings are only removed during * a write operation, although this method is called for both * read and write operations to maintain a consistent state. *

          * 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. */ private void purge() { Reference ref = queue.poll(); while (ref != null) { purge(ref); ref = queue.poll(); } } private 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 = indexFor(hash); Entry previous = null; Entry entry = table[index]; while (entry != null) { if (entry.purge(ref)) { if (previous == null) table[index] = entry.next; else previous.next = entry.next; this.size--; return; } previous = entry; entry = entry.next; } } /** * Returns the size of this map. * * @return the size of this map */ public int size() { purge(); return size; } /** * Returns true if this map is empty. * * @return true if this map is empty */ public boolean isEmpty() { purge(); return size == 0; } /** * Returns true if this map contains the given key. * * @return true if the given key is in this map */ public boolean containsKey(Object key) { purge(); Entry entry = getEntry(key); if (entry == null) return false; return entry.getValue() != null; } /** * Returns the value associated with the given key, if any. * * @return the value associated with the given key, or null * if the key maps to no value */ public Object get(Object key) { purge(); Entry entry = getEntry(key); if (entry == null) return null; return entry.getValue(); } /** * Associates the given key with the given value.

          * Neither the key nor the value may be null. * * @param key the key of the mapping * @param value the value of the mapping * @return the last value associated with that key, or * null if no value was associated with the key * @throws NullPointerException if either the key or value * is null */ public Object put(Object key, Object value) { if (key == null) throw new NullPointerException("null keys not allowed"); if (value == null) throw new NullPointerException("null values not allowed"); purge(); if (size + 1 > threshold) resize(); int hash = key.hashCode(); int index = indexFor(hash); Entry entry = table[index]; while (entry != null) { if ((hash == entry.hash) && key.equals(entry.getKey())) { Object result = entry.getValue(); entry.setValue(value); return result; } entry = entry.next; } this.size++; modCount++; key = toReference(keyType, key, hash); value = toReference(valueType, value, hash); table[index] = new Entry(key, hash, value, table[index]); return null; } /** * Removes the key and its associated value from this map. * * @param key the key to remove * @return the value associated with that key, or null if * the key was not in the map */ public Object remove(Object key) { if (key == null) return null; purge(); int hash = key.hashCode(); int index = indexFor(hash); Entry previous = null; Entry entry = table[index]; while (entry != null) { if ((hash == entry.hash) && key.equals(entry.getKey())) { if (previous == null) table[index] = entry.next; else previous.next = entry.next; this.size--; modCount++; return entry.getValue(); } previous = entry; entry = entry.next; } return null; } /** * Clears this map. */ public void clear() { Arrays.fill(table, null); size = 0; while (queue.poll() != null); // drain the queue } /** * Returns a set view of this map's entries. * * @return a set view of this map's entries */ public Set entrySet() { if (entrySet != null) { return entrySet; } entrySet = new AbstractSet() { public int size() { return ReferenceMap.this.size(); } public void clear() { ReferenceMap.this.clear(); } public boolean contains(Object o) { if (o == null) return false; if (!(o instanceof Map.Entry)) return false; Map.Entry e = (Map.Entry)o; Entry e2 = getEntry(e.getKey()); return (e2 != null) && e.equals(e2); } public boolean remove(Object o) { boolean r = contains(o); if (r) { Map.Entry e = (Map.Entry)o; ReferenceMap.this.remove(e.getKey()); } return r; } public Iterator iterator() { return new EntryIterator(); } public Object[] toArray() { return toArray(new Object[0]); } public Object[] toArray(Object[] arr) { ArrayList list = new ArrayList(); Iterator iterator = iterator(); while (iterator.hasNext()) { Entry e = (Entry)iterator.next(); list.add(new DefaultMapEntry(e.getKey(), e.getValue())); } return list.toArray(arr); } }; 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) return keySet; keySet = new AbstractSet() { public int size() { return ReferenceMap.this.size(); } public Iterator iterator() { return new KeyIterator(); } public boolean contains(Object o) { return containsKey(o); } public boolean remove(Object o) { Object r = ReferenceMap.this.remove(o); return r != null; } public void clear() { ReferenceMap.this.clear(); } public Object[] toArray() { return toArray(new Object[0]); } public Object[] toArray(Object[] array) { Collection c = new ArrayList(size()); for (Iterator it = iterator(); it.hasNext(); ) { c.add(it.next()); } return c.toArray(array); } }; return keySet; } /** * Returns a collection view of this map's values. * * @return a collection view of this map's values. */ public Collection values() { if (values != null) return values; values = new AbstractCollection() { public int size() { return ReferenceMap.this.size(); } public void clear() { ReferenceMap.this.clear(); } public Iterator iterator() { return new ValueIterator(); } public Object[] toArray() { return toArray(new Object[0]); } public Object[] toArray(Object[] array) { Collection c = new ArrayList(size()); for (Iterator it = iterator(); it.hasNext(); ) { c.add(it.next()); } return c.toArray(array); } }; return values; } // If getKey() or getValue() returns null, it means // the mapping is stale and should be removed. private class Entry implements Map.Entry, KeyValue { Object key; Object value; int hash; Entry next; public Entry(Object key, int hash, Object value, Entry next) { this.key = key; this.hash = hash; this.value = value; this.next = next; } public Object getKey() { return (keyType > HARD) ? ((Reference)key).get() : key; } public Object getValue() { return (valueType > HARD) ? ((Reference)value).get() : value; } public Object setValue(Object object) { Object old = getValue(); if (valueType > HARD) ((Reference)value).clear(); value = toReference(valueType, object, hash); return old; } public boolean equals(Object o) { if (o == null) return false; if (o == this) return true; if (!(o instanceof Map.Entry)) return false; Map.Entry entry = (Map.Entry)o; Object key = entry.getKey(); Object value = entry.getValue(); if ((key == null) || (value == null)) return false; return key.equals(getKey()) && value.equals(getValue()); } public int hashCode() { Object v = getValue(); return hash ^ ((v == null) ? 0 : v.hashCode()); } public String toString() { return getKey() + "=" + getValue(); } boolean purge(Reference ref) { boolean r = (keyType > HARD) && (key == ref); r = r || ((valueType > HARD) && (value == ref)); if (r) { if (keyType > HARD) ((Reference)key).clear(); if (valueType > HARD) { ((Reference)value).clear(); } else if (purgeValues) { value = null; } } return r; } } private class EntryIterator implements Iterator { // These fields keep track of where we are in the table. int index; Entry entry; Entry 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. Object nextKey, nextValue; Object currentKey, currentValue; int expectedModCount; public EntryIterator() { index = (size() != 0 ? table.length : 0); // have to do this here! size() invocation above // may have altered the modCount. expectedModCount = modCount; } public boolean hasNext() { checkMod(); while (nextNull()) { Entry e = entry; int i = index; while ((e == null) && (i > 0)) { i--; e = table[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 (modCount != expectedModCount) { throw new ConcurrentModificationException(); } } private boolean nextNull() { return (nextKey == null) || (nextValue == null); } protected Entry nextEntry() { checkMod(); if (nextNull() && !hasNext()) throw new NoSuchElementException(); previous = entry; entry = entry.next; currentKey = nextKey; currentValue = nextValue; nextKey = null; nextValue = null; return previous; } public Object next() { return nextEntry(); } public void remove() { checkMod(); if (previous == null) throw new IllegalStateException(); ReferenceMap.this.remove(currentKey); previous = null; currentKey = null; currentValue = null; expectedModCount = modCount; } } private class ValueIterator extends EntryIterator { public Object next() { return nextEntry().getValue(); } } private class KeyIterator extends EntryIterator { public Object next() { return nextEntry().getKey(); } } // 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. private static class SoftRef extends SoftReference { private int hash; public SoftRef(int hash, Object r, ReferenceQueue q) { super(r, q); this.hash = hash; } public int hashCode() { return hash; } } private static class WeakRef extends WeakReference { private int hash; public WeakRef(int hash, Object r, ReferenceQueue q) { super(r, q); this.hash = hash; } public int hashCode() { return hash; } } } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/ResettableIterator.java0000644000175000017500000000260610777673522032005 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; 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. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ public interface ResettableIterator extends Iterator { /** * Resets the iterator back to the position at which the iterator * was created. */ public void reset(); } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/ResettableListIterator.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/ResettableListIterator.jav0000644000175000017500000000265210777673521032500 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; 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. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ public interface ResettableListIterator extends ListIterator, ResettableIterator { /** * Resets the iterator back to the position at which the iterator * was created. */ public void reset(); } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/SequencedHashMap.java0000644000175000017500000011030310777673522031351 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; import java.io.Externalizable; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.AbstractCollection; import java.util.AbstractSet; import java.util.ArrayList; import java.util.Collection; import java.util.ConcurrentModificationException; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; import org.apache.commons.collections.list.UnmodifiableList; /** * A map of objects whose mapping entries are sequenced based on the order in * which they were added. This data structure has fast O(1) search * time, deletion time, and insertion time. *

          * Although this map is sequenced, it cannot implement * {@link java.util.List} because of incompatible interface definitions. * The remove methods in List and Map have different return values * (see: {@link java.util.List#remove(Object)} and {@link java.util.Map#remove(Object)}). *

          * This class is not thread safe. When a thread safe implementation is * required, use {@link java.util.Collections#synchronizedMap(Map)} as it is documented, * or use explicit synchronization controls. * * @deprecated Replaced by LinkedMap and ListOrderedMap in map subpackage. Due to be removed in v4.0. * @see org.apache.commons.collections.map.LinkedMap * @see org.apache.commons.collections.map.ListOrderedMap * @since Commons Collections 2.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Michael A. Smith * @author Daniel Rall * @author Henning P. Schmiedehausen * @author Stephen Colebourne */ public class SequencedHashMap implements Map, Cloneable, Externalizable { /** * {@link java.util.Map.Entry} that doubles as a node in the linked list * of sequenced mappings. */ private static class Entry implements Map.Entry, KeyValue { // Note: This class cannot easily be made clonable. While the actual // implementation of a clone would be simple, defining the semantics is // difficult. If a shallow clone is implemented, then entry.next.prev != // entry, which is unintuitive and probably breaks all sorts of assumptions // in code that uses this implementation. If a deep clone is // implemented, then what happens when the linked list is cyclical (as is // the case with SequencedHashMap)? It's impossible to know in the clone // when to stop cloning, and thus you end up in a recursive loop, // continuously cloning the "next" in the list. private final Object key; private Object value; // package private to allow the SequencedHashMap to access and manipulate // them. Entry next = null; Entry prev = null; public Entry(Object key, Object value) { this.key = key; this.value = value; } // per Map.Entry.getKey() public Object getKey() { return this.key; } // per Map.Entry.getValue() public Object getValue() { return this.value; } // per Map.Entry.setValue() public Object setValue(Object value) { Object oldValue = this.value; this.value = value; return oldValue; } public int hashCode() { // implemented per api docs for Map.Entry.hashCode() return ((getKey() == null ? 0 : getKey().hashCode()) ^ (getValue() == null ? 0 : getValue().hashCode())); } public boolean equals(Object obj) { if (obj == null) return false; if (obj == this) return true; if (!(obj instanceof Map.Entry)) return false; Map.Entry other = (Map.Entry) obj; // implemented per api docs for Map.Entry.equals(Object) return ( (getKey() == null ? other.getKey() == null : getKey().equals(other.getKey())) && (getValue() == null ? other.getValue() == null : getValue().equals(other.getValue()))); } public String toString() { return "[" + getKey() + "=" + getValue() + "]"; } } /** * Construct an empty sentinel used to hold the head (sentinel.next) and the * tail (sentinel.prev) of the list. The sentinel has a null * key and value. */ private static final Entry createSentinel() { Entry s = new Entry(null, null); s.prev = s; s.next = s; return s; } /** * Sentinel used to hold the head and tail of the list of entries. */ private Entry sentinel; /** * Map of keys to entries */ private HashMap entries; /** * Holds the number of modifications that have occurred to the map, * excluding modifications made through a collection view's iterator * (e.g. entrySet().iterator().remove()). This is used to create a * fail-fast behavior with the iterators. */ private transient long modCount = 0; /** * Construct a new sequenced hash map with default initial size and load * factor. */ public SequencedHashMap() { sentinel = createSentinel(); entries = new HashMap(); } /** * Construct a new sequenced hash map with the specified initial size and * default load factor. * * @param initialSize the initial size for the hash table * * @see HashMap#HashMap(int) */ public SequencedHashMap(int initialSize) { sentinel = createSentinel(); entries = new HashMap(initialSize); } /** * Construct a new sequenced hash map with the specified initial size and * load factor. * * @param initialSize the initial size for the hash table * * @param loadFactor the load factor for the hash table. * * @see HashMap#HashMap(int,float) */ public SequencedHashMap(int initialSize, float loadFactor) { sentinel = createSentinel(); entries = new HashMap(initialSize, loadFactor); } /** * Construct a new sequenced hash map and add all the elements in the * specified map. The order in which the mappings in the specified map are * added is defined by {@link #putAll(Map)}. */ public SequencedHashMap(Map m) { this(); putAll(m); } /** * Removes an internal entry from the linked list. This does not remove * it from the underlying map. */ private void removeEntry(Entry entry) { entry.next.prev = entry.prev; entry.prev.next = entry.next; } /** * Inserts a new internal entry to the tail of the linked list. This does * not add the entry to the underlying map. */ private void insertEntry(Entry entry) { entry.next = sentinel; entry.prev = sentinel.prev; sentinel.prev.next = entry; sentinel.prev = entry; } // per Map.size() /** * Implements {@link Map#size()}. */ public int size() { // use the underlying Map's size since size is not maintained here. return entries.size(); } /** * Implements {@link Map#isEmpty()}. */ public boolean isEmpty() { // for quick check whether the map is entry, we can check the linked list // and see if there's anything in it. return sentinel.next == sentinel; } /** * Implements {@link Map#containsKey(Object)}. */ public boolean containsKey(Object key) { // pass on to underlying map implementation return entries.containsKey(key); } /** * Implements {@link Map#containsValue(Object)}. */ public boolean containsValue(Object value) { // unfortunately, we cannot just pass this call to the underlying map // because we are mapping keys to entries, not keys to values. The // underlying map doesn't have an efficient implementation anyway, so this // isn't a big deal. // do null comparison outside loop so we only need to do it once. This // provides a tighter, more efficient loop at the expense of slight // code duplication. if (value == null) { for (Entry pos = sentinel.next; pos != sentinel; pos = pos.next) { if (pos.getValue() == null) return true; } } else { for (Entry pos = sentinel.next; pos != sentinel; pos = pos.next) { if (value.equals(pos.getValue())) return true; } } return false; } /** * Implements {@link Map#get(Object)}. */ public Object get(Object o) { // find entry for the specified key object Entry entry = (Entry) entries.get(o); if (entry == null) return null; return entry.getValue(); } /** * Return the entry for the "oldest" mapping. That is, return the Map.Entry * for the key-value pair that was first put into the map when compared to * all the other pairings in the map. This behavior is equivalent to using * entrySet().iterator().next(), but this method provides an * optimized implementation. * * @return The first entry in the sequence, or null if the * map is empty. */ public Map.Entry getFirst() { // sentinel.next points to the "first" element of the sequence -- the head // of the list, which is exactly the entry we need to return. We must test // for an empty list though because we don't want to return the sentinel! return (isEmpty()) ? null : sentinel.next; } /** * Return the key for the "oldest" mapping. That is, return the key for the * mapping that was first put into the map when compared to all the other * objects in the map. This behavior is equivalent to using * getFirst().getKey(), but this method provides a slightly * optimized implementation. * * @return The first key in the sequence, or null if the * map is empty. */ public Object getFirstKey() { // sentinel.next points to the "first" element of the sequence -- the head // of the list -- and the requisite key is returned from it. An empty list // does not need to be tested. In cases where the list is empty, // sentinel.next will point to the sentinel itself which has a null key, // which is exactly what we would want to return if the list is empty (a // nice convenient way to avoid test for an empty list) return sentinel.next.getKey(); } /** * Return the value for the "oldest" mapping. That is, return the value for * the mapping that was first put into the map when compared to all the * other objects in the map. This behavior is equivalent to using * getFirst().getValue(), but this method provides a slightly * optimized implementation. * * @return The first value in the sequence, or null if the * map is empty. */ public Object getFirstValue() { // sentinel.next points to the "first" element of the sequence -- the head // of the list -- and the requisite value is returned from it. An empty // list does not need to be tested. In cases where the list is empty, // sentinel.next will point to the sentinel itself which has a null value, // which is exactly what we would want to return if the list is empty (a // nice convenient way to avoid test for an empty list) return sentinel.next.getValue(); } /** * Return the entry for the "newest" mapping. That is, return the Map.Entry * for the key-value pair that was first put into the map when compared to * all the other pairings in the map. The behavior is equivalent to: * *

               *    Object obj = null;
               *    Iterator iter = entrySet().iterator();
               *    while(iter.hasNext()) {
               *      obj = iter.next();
               *    }
               *    return (Map.Entry)obj;
               *  
          * * However, the implementation of this method ensures an O(1) lookup of the * last key rather than O(n). * * @return The last entry in the sequence, or null if the map * is empty. */ public Map.Entry getLast() { // sentinel.prev points to the "last" element of the sequence -- the tail // of the list, which is exactly the entry we need to return. We must test // for an empty list though because we don't want to return the sentinel! return (isEmpty()) ? null : sentinel.prev; } /** * Return the key for the "newest" mapping. That is, return the key for the * mapping that was last put into the map when compared to all the other * objects in the map. This behavior is equivalent to using * getLast().getKey(), but this method provides a slightly * optimized implementation. * * @return The last key in the sequence, or null if the map is * empty. */ public Object getLastKey() { // sentinel.prev points to the "last" element of the sequence -- the tail // of the list -- and the requisite key is returned from it. An empty list // does not need to be tested. In cases where the list is empty, // sentinel.prev will point to the sentinel itself which has a null key, // which is exactly what we would want to return if the list is empty (a // nice convenient way to avoid test for an empty list) return sentinel.prev.getKey(); } /** * Return the value for the "newest" mapping. That is, return the value for * the mapping that was last put into the map when compared to all the other * objects in the map. This behavior is equivalent to using * getLast().getValue(), but this method provides a slightly * optimized implementation. * * @return The last value in the sequence, or null if the map * is empty. */ public Object getLastValue() { // sentinel.prev points to the "last" element of the sequence -- the tail // of the list -- and the requisite value is returned from it. An empty // list does not need to be tested. In cases where the list is empty, // sentinel.prev will point to the sentinel itself which has a null value, // which is exactly what we would want to return if the list is empty (a // nice convenient way to avoid test for an empty list) return sentinel.prev.getValue(); } /** * Implements {@link Map#put(Object, Object)}. */ public Object put(Object key, Object value) { modCount++; Object oldValue = null; // lookup the entry for the specified key Entry e = (Entry) entries.get(key); // check to see if it already exists if (e != null) { // remove from list so the entry gets "moved" to the end of list removeEntry(e); // update value in map oldValue = e.setValue(value); // Note: We do not update the key here because its unnecessary. We only // do comparisons using equals(Object) and we know the specified key and // that in the map are equal in that sense. This may cause a problem if // someone does not implement their hashCode() and/or equals(Object) // method properly and then use it as a key in this map. } else { // add new entry e = new Entry(key, value); entries.put(key, e); } // assert(entry in map, but not list) // add to list insertEntry(e); return oldValue; } /** * Implements {@link Map#remove(Object)}. */ public Object remove(Object key) { Entry e = removeImpl(key); return (e == null) ? null : e.getValue(); } /** * Fully remove an entry from the map, returning the old entry or null if * there was no such entry with the specified key. */ private Entry removeImpl(Object key) { Entry e = (Entry) entries.remove(key); if (e == null) return null; modCount++; removeEntry(e); return e; } /** * Adds all the mappings in the specified map to this map, replacing any * mappings that already exist (as per {@link Map#putAll(Map)}). The order * in which the entries are added is determined by the iterator returned * from {@link Map#entrySet()} for the specified map. * * @param t the mappings that should be added to this map. * * @throws NullPointerException if t is null */ public void putAll(Map t) { Iterator iter = t.entrySet().iterator(); while (iter.hasNext()) { Map.Entry entry = (Map.Entry) iter.next(); put(entry.getKey(), entry.getValue()); } } /** * Implements {@link Map#clear()}. */ public void clear() { modCount++; // remove all from the underlying map entries.clear(); // and the list sentinel.next = sentinel; sentinel.prev = sentinel; } /** * Implements {@link Map#equals(Object)}. */ public boolean equals(Object obj) { if (obj == null) return false; if (obj == this) return true; if (!(obj instanceof Map)) return false; return entrySet().equals(((Map) obj).entrySet()); } /** * Implements {@link Map#hashCode()}. */ public int hashCode() { return entrySet().hashCode(); } /** * Provides a string representation of the entries within the map. The * format of the returned string may change with different releases, so this * method is suitable for debugging purposes only. If a specific format is * required, use {@link #entrySet()}.{@link Set#iterator() iterator()} and * iterate over the entries in the map formatting them as appropriate. */ public String toString() { StringBuffer buf = new StringBuffer(); buf.append('['); for (Entry pos = sentinel.next; pos != sentinel; pos = pos.next) { buf.append(pos.getKey()); buf.append('='); buf.append(pos.getValue()); if (pos.next != sentinel) { buf.append(','); } } buf.append(']'); return buf.toString(); } /** * Implements {@link Map#keySet()}. */ public Set keySet() { return new AbstractSet() { // required impls public Iterator iterator() { return new OrderedIterator(KEY); } public boolean remove(Object o) { Entry e = SequencedHashMap.this.removeImpl(o); return (e != null); } // more efficient impls than abstract set public void clear() { SequencedHashMap.this.clear(); } public int size() { return SequencedHashMap.this.size(); } public boolean isEmpty() { return SequencedHashMap.this.isEmpty(); } public boolean contains(Object o) { return SequencedHashMap.this.containsKey(o); } }; } /** * Implements {@link Map#values()}. */ public Collection values() { return new AbstractCollection() { // required impl public Iterator iterator() { return new OrderedIterator(VALUE); } public boolean remove(Object value) { // do null comparison outside loop so we only need to do it once. This // provides a tighter, more efficient loop at the expense of slight // code duplication. if (value == null) { for (Entry pos = sentinel.next; pos != sentinel; pos = pos.next) { if (pos.getValue() == null) { SequencedHashMap.this.removeImpl(pos.getKey()); return true; } } } else { for (Entry pos = sentinel.next; pos != sentinel; pos = pos.next) { if (value.equals(pos.getValue())) { SequencedHashMap.this.removeImpl(pos.getKey()); return true; } } } return false; } // more efficient impls than abstract collection public void clear() { SequencedHashMap.this.clear(); } public int size() { return SequencedHashMap.this.size(); } public boolean isEmpty() { return SequencedHashMap.this.isEmpty(); } public boolean contains(Object o) { return SequencedHashMap.this.containsValue(o); } }; } /** * Implements {@link Map#entrySet()}. */ public Set entrySet() { return new AbstractSet() { // helper private Entry findEntry(Object o) { if (o == null) return null; if (!(o instanceof Map.Entry)) return null; Map.Entry e = (Map.Entry) o; Entry entry = (Entry) entries.get(e.getKey()); if (entry != null && entry.equals(e)) return entry; else return null; } // required impl public Iterator iterator() { return new OrderedIterator(ENTRY); } public boolean remove(Object o) { Entry e = findEntry(o); if (e == null) return false; return SequencedHashMap.this.removeImpl(e.getKey()) != null; } // more efficient impls than abstract collection public void clear() { SequencedHashMap.this.clear(); } public int size() { return SequencedHashMap.this.size(); } public boolean isEmpty() { return SequencedHashMap.this.isEmpty(); } public boolean contains(Object o) { return findEntry(o) != null; } }; } // constants to define what the iterator should return on "next" private static final int KEY = 0; private static final int VALUE = 1; private static final int ENTRY = 2; private static final int REMOVED_MASK = 0x80000000; private class OrderedIterator implements Iterator { /** * Holds the type that should be returned from the iterator. The value * should be either {@link #KEY}, {@link #VALUE}, or {@link #ENTRY}. To * save a tiny bit of memory, this field is also used as a marker for when * remove has been called on the current object to prevent a second remove * on the same element. Essentially, if this value is negative (i.e. the * bit specified by {@link #REMOVED_MASK} is set), the current position * has been removed. If positive, remove can still be called. */ private int returnType; /** * Holds the "current" position in the iterator. When pos.next is the * sentinel, we've reached the end of the list. */ private Entry pos = sentinel; /** * Holds the expected modification count. If the actual modification * count of the map differs from this value, then a concurrent * modification has occurred. */ private transient long expectedModCount = modCount; /** * Construct an iterator over the sequenced elements in the order in which * they were added. The {@link #next()} method returns the type specified * by returnType which must be either {@link #KEY}, {@link * #VALUE}, or {@link #ENTRY}. */ public OrderedIterator(int returnType) { //// Since this is a private inner class, nothing else should have //// access to the constructor. Since we know the rest of the outer //// class uses the iterator correctly, we can leave of the following //// check: //if(returnType >= 0 && returnType <= 2) { // throw new IllegalArgumentException("Invalid iterator type"); //} // Set the "removed" bit so that the iterator starts in a state where // "next" must be called before "remove" will succeed. this.returnType = returnType | REMOVED_MASK; } /** * Returns whether there is any additional elements in the iterator to be * returned. * * @return true if there are more elements left to be * returned from the iterator; false otherwise. */ public boolean hasNext() { return pos.next != sentinel; } /** * Returns the next element from the iterator. * * @return the next element from the iterator. * * @throws NoSuchElementException if there are no more elements in the * iterator. * * @throws ConcurrentModificationException if a modification occurs in * the underlying map. */ public Object next() { if (modCount != expectedModCount) { throw new ConcurrentModificationException(); } if (pos.next == sentinel) { throw new NoSuchElementException(); } // clear the "removed" flag returnType = returnType & ~REMOVED_MASK; pos = pos.next; switch (returnType) { case KEY : return pos.getKey(); case VALUE : return pos.getValue(); case ENTRY : return pos; default : // should never happen throw new Error("bad iterator type: " + returnType); } } /** * Removes the last element returned from the {@link #next()} method from * the sequenced map. * * @throws IllegalStateException if there isn't a "last element" to be * removed. That is, if {@link #next()} has never been called, or if * {@link #remove()} was already called on the element. * * @throws ConcurrentModificationException if a modification occurs in * the underlying map. */ public void remove() { if ((returnType & REMOVED_MASK) != 0) { throw new IllegalStateException("remove() must follow next()"); } if (modCount != expectedModCount) { throw new ConcurrentModificationException(); } SequencedHashMap.this.removeImpl(pos.getKey()); // update the expected mod count for the remove operation expectedModCount++; // set the removed flag returnType = returnType | REMOVED_MASK; } } // APIs maintained from previous version of SequencedHashMap for backwards // compatibility /** * Creates a shallow copy of this object, preserving the internal structure * by copying only references. The keys and values themselves are not * clone()'d. The cloned object maintains the same sequence. * * @return A clone of this instance. * * @throws CloneNotSupportedException if clone is not supported by a * subclass. */ public Object clone() throws CloneNotSupportedException { // yes, calling super.clone() silly since we're just blowing away all // the stuff that super might be doing anyway, but for motivations on // this, see: // http://www.javaworld.com/javaworld/jw-01-1999/jw-01-object.html SequencedHashMap map = (SequencedHashMap) super.clone(); // create new, empty sentinel map.sentinel = createSentinel(); // create a new, empty entry map // note: this does not preserve the initial capacity and load factor. map.entries = new HashMap(); // add all the mappings map.putAll(this); // Note: We cannot just clone the hashmap and sentinel because we must // duplicate our internal structures. Cloning those two will not clone all // the other entries they reference, and so the cloned hash map will not be // able to maintain internal consistency because there are two objects with // the same entries. See discussion in the Entry implementation on why we // cannot implement a clone of the Entry (and thus why we need to recreate // everything). return map; } /** * Returns the Map.Entry at the specified index * * @throws ArrayIndexOutOfBoundsException if the specified index is * < 0 or > the size of the map. */ private Map.Entry getEntry(int index) { Entry pos = sentinel; if (index < 0) { throw new ArrayIndexOutOfBoundsException(index + " < 0"); } // loop to one before the position int i = -1; while (i < (index - 1) && pos.next != sentinel) { i++; pos = pos.next; } // pos.next is the requested position // if sentinel is next, past end of list if (pos.next == sentinel) { throw new ArrayIndexOutOfBoundsException(index + " >= " + (i + 1)); } return pos.next; } /** * Gets the key at the specified index. * * @param index the index to retrieve * @return the key at the specified index, or null * @throws ArrayIndexOutOfBoundsException if the index is * < 0 or > the size of the map. */ public Object get(int index) { return getEntry(index).getKey(); } /** * Gets the value at the specified index. * * @param index the index to retrieve * @return the value at the specified index, or null * @throws ArrayIndexOutOfBoundsException if the index is * < 0 or > the size of the map. */ public Object 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) { Entry e = (Entry) entries.get(key); if (e == null) { return -1; } int pos = 0; while (e.prev != sentinel) { pos++; e = e.prev; } return pos; } /** * Gets an iterator over the keys. * * @return an iterator over the keys */ public Iterator iterator() { return keySet().iterator(); } /** * Gets the last index of the specified key. * * @param key the key to find the index of * @return the index, or -1 if not found */ public int lastIndexOf(Object key) { // keys in a map are guaranteed to be unique return indexOf(key); } /** * Returns a List view of the keys rather than a set view. The returned * list is unmodifiable. This is required 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()} * * @see #keySet() * @return The ordered list of keys. */ public List sequence() { List l = new ArrayList(size()); Iterator iter = keySet().iterator(); while (iter.hasNext()) { l.add(iter.next()); } return UnmodifiableList.decorate(l); } /** * 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 ArrayIndexOutOfBoundsException if the index is * < 0 or > the size of the map. */ public Object remove(int index) { return remove(get(index)); } // per Externalizable.readExternal(ObjectInput) /** * Deserializes this map from the given stream. * * @param in the stream to deserialize from * @throws IOException if the stream raises it * @throws ClassNotFoundException if the stream raises it */ public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { int size = in.readInt(); for (int i = 0; i < size; i++) { Object key = in.readObject(); Object value = in.readObject(); put(key, value); } } /** * Serializes this map to the given stream. * * @param out the stream to serialize to * @throws IOException if the stream raises it */ public void writeExternal(ObjectOutput out) throws IOException { out.writeInt(size()); for (Entry pos = sentinel.next; pos != sentinel; pos = pos.next) { out.writeObject(pos.getKey()); out.writeObject(pos.getValue()); } } // add a serial version uid, so that if we change things in the future // without changing the format, we can still deserialize properly. private static final long serialVersionUID = 3380552487888102930L; } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/SetUtils.java0000644000175000017500000003107010777673521027751 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import org.apache.commons.collections.set.ListOrderedSet; import org.apache.commons.collections.set.PredicatedSet; import org.apache.commons.collections.set.PredicatedSortedSet; import org.apache.commons.collections.set.SynchronizedSet; import org.apache.commons.collections.set.SynchronizedSortedSet; import org.apache.commons.collections.set.TransformedSet; import org.apache.commons.collections.set.TransformedSortedSet; import org.apache.commons.collections.set.TypedSet; import org.apache.commons.collections.set.TypedSortedSet; import org.apache.commons.collections.set.UnmodifiableSet; import org.apache.commons.collections.set.UnmodifiableSortedSet; /** * Provides utility methods and decorators for * {@link Set} and {@link SortedSet} instances. * * @since Commons Collections 2.1 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Paul Jack * @author Stephen Colebourne * @author Neil O'Toole * @author Matthew Hawthorne */ 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).

          *
          * * @see java.util.Set * @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 */ 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. * * @see java.util.Set#hashCode() * @param set the set to calculate the hash code for, may be null * @return the hash code */ 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 */ 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 */ 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); } } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/SortedBag.java0000644000175000017500000000340310777673521030046 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; import java.util.Comparator; /** * Defines a type of Bag that maintains a sorted order among * its unique representative members. * * @since Commons Collections 2.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Chuck Burdick */ 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 Object first(); /** * Returns the last (highest) member. * * @return the last element in the sorted bag */ public Object last(); } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/SortedBidiMap.java0000644000175000017500000000554410777673522030673 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; 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. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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(); } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/StaticBucketMap.java0000644000175000017500000005031510777673521031223 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; import java.util.AbstractCollection; import java.util.AbstractSet; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; /** * 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.

          * * @deprecated Moved to map subpackage. Due to be removed in v4.0. * @since Commons Collections 2.1 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Berin Loritsch * @author Gerhard Froehlich * @author Michael A. Smith * @author Paul Jack * @author Leo Sutic * @author Janek Bogucki * @author Kazuya Ujihara */ public final class StaticBucketMap implements Map { private static final int DEFAULT_BUCKETS = 255; private Node[] m_buckets; private Lock[] m_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--; } m_buckets = new Node[ size ]; m_locks = new Lock[ size ]; for( int i = 0; i < size; i++ ) { m_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 %= m_buckets.length; return ( hash < 0 ) ? hash * -1 : hash; } /** * Implements {@link Map#keySet()}. */ public Set keySet() { return new KeySet(); } /** * Implements {@link Map#size()}. */ public int size() { int cnt = 0; for( int i = 0; i < m_buckets.length; i++ ) { cnt += m_locks[i].size; } return cnt; } /** * Implements {@link Map#put(Object, Object)}. */ public Object put( final Object key, final Object value ) { int hash = getHash( key ); synchronized( m_locks[ hash ] ) { Node n = m_buckets[ hash ]; if( n == null ) { n = new Node(); n.key = key; n.value = value; m_buckets[ hash ] = n; m_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 ) ) ) { Object 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; m_locks[hash].size++; } return null; } /** * Implements {@link Map#get(Object)}. */ public Object get( final Object key ) { int hash = getHash( key ); synchronized( m_locks[ hash ] ) { Node n = m_buckets[ hash ]; while( n != null ) { if( n.key == key || ( n.key != null && n.key.equals( key ) ) ) { return n.value; } n = n.next; } } return null; } /** * Implements {@link Map#containsKey(Object)}. */ public boolean containsKey( final Object key ) { int hash = getHash( key ); synchronized( m_locks[ hash ] ) { Node n = m_buckets[ hash ]; while( n != null ) { if( n.key == key || ( n.key != null && n.key.equals( key ) ) ) { return true; } n = n.next; } } return false; } /** * Implements {@link Map#containsValue(Object)}. */ public boolean containsValue( final Object value ) { for( int i = 0; i < m_buckets.length; i++ ) { synchronized( m_locks[ i ] ) { Node n = m_buckets[ i ]; while( n != null ) { if( n.value == value || (n.value != null && n.value.equals( value ) ) ) { return true; } n = n.next; } } } return false; } /** * Implements {@link Map#values()}. */ public Collection values() { return new Values(); } /** * Implements {@link Map#entrySet()}. */ public Set entrySet() { return new EntrySet(); } /** * Implements {@link Map#putAll(Map)}. */ public void putAll( Map other ) { Iterator i = other.keySet().iterator(); while( i.hasNext() ) { Object key = i.next(); put( key, other.get( key ) ); } } /** * Implements {@link Map#remove(Object)}. */ public Object remove( Object key ) { int hash = getHash( key ); synchronized( m_locks[ hash ] ) { Node n = m_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. m_buckets[ hash ] = n.next; } else { // Set the next node of the previous node to be the node after this one. prev.next = n.next; } m_locks[hash].size--; return n.value; } prev = n; n = n.next; } } return null; } /** * Implements {@link Map#isEmpty()}. */ public final boolean isEmpty() { return size() == 0; } /** * Implements {@link Map#clear()}. */ public final void clear() { for( int i = 0; i < m_buckets.length; i++ ) { Lock lock = m_locks[i]; synchronized (lock) { m_buckets[ i ] = null; lock.size = 0; } } } /** * Implements {@link Map#equals(Object)}. */ public final boolean equals( Object obj ) { if( obj == null ) return false; if( obj == this ) return true; if( !( obj instanceof Map ) ) return false; Map other = (Map)obj; return entrySet().equals(other.entrySet()); } /** * Implements {@link Map#hashCode()}. */ public final int hashCode() { int hashCode = 0; for( int i = 0; i < m_buckets.length; i++ ) { synchronized( m_locks[ i ] ) { Node n = m_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 Object key; protected Object value; protected Node next; public Object getKey() { return key; } public Object getValue() { return value; } public int hashCode() { return ( ( key == null ? 0 : key.hashCode() ) ^ ( value == null ? 0 : value.hashCode() ) ); } public boolean equals(Object o) { if( o == null ) return false; if( o == this ) return true; if ( ! (o instanceof Map.Entry ) ) return false; Map.Entry e2 = (Map.Entry)o; return ((key == null ? e2.getKey() == null : key.equals(e2.getKey())) && (value == null ? e2.getValue() == null : value.equals(e2.getValue()))); } public Object setValue( Object val ) { Object retVal = value; value = val; return retVal; } } private final static class Lock { public int size; } private class EntryIterator implements Iterator { private ArrayList current = new ArrayList(); private int bucket; private Map.Entry last; public boolean hasNext() { if (current.size() > 0) return true; while (bucket < m_buckets.length) { synchronized (m_locks[bucket]) { Node n = m_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 = (Map.Entry)current.remove(current.size() - 1); return last; } public Object next() { return nextEntry(); } public void remove() { if (last == null) throw new IllegalStateException(); StaticBucketMap.this.remove(last.getKey()); last = null; } } private class ValueIterator extends EntryIterator { public Object next() { return nextEntry().getValue(); } } private class KeyIterator extends EntryIterator { public Object 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 o) { Map.Entry entry = (Map.Entry)o; int hash = getHash(entry.getKey()); synchronized (m_locks[hash]) { for (Node n = m_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 (m_locks[hash]) { for (Node n = m_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 o) { return StaticBucketMap.this.containsKey(o); } public boolean remove(Object o) { int hash = getHash(o); synchronized (m_locks[hash]) { for (Node n = m_buckets[hash]; n != null; n = n.next) { Object k = n.getKey(); if ((k == o) || ((k != null) && k.equals(o))) { 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 >= m_buckets.length) { r.run(); return; } synchronized (m_locks[bucket]) { atomic(r, bucket + 1); } } } ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootlibcommons-collections3-java.orig/src/java/org/apache/commons/collections/SynchronizedPriorityQueue.javalibcommons-collections3-java.orig/src/java/org/apache/commons/collections/SynchronizedPriorityQueue.0000644000175000017500000000627310777673522032571 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; import java.util.NoSuchElementException; /** * A thread safe version of the PriorityQueue. * Provides synchronized wrapper methods for all the methods * defined in the PriorityQueue interface. * * @deprecated PriorityQueue is replaced by the Buffer interface, see buffer subpackage. * Due to be removed in v4.0. * @since Commons Collections 1.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Ram Chidambaram */ public final class SynchronizedPriorityQueue implements PriorityQueue { /** * The underlying priority queue. */ protected final PriorityQueue m_priorityQueue; /** * Constructs a new synchronized priority queue. * * @param priorityQueue the priority queue to synchronize */ public SynchronizedPriorityQueue(final PriorityQueue priorityQueue) { m_priorityQueue = priorityQueue; } /** * Clear all elements from queue. */ public synchronized void clear() { m_priorityQueue.clear(); } /** * Test if queue is empty. * * @return true if queue is empty else false. */ public synchronized boolean isEmpty() { return m_priorityQueue.isEmpty(); } /** * Insert an element into queue. * * @param element the element to be inserted */ public synchronized void insert(final Object element) { m_priorityQueue.insert(element); } /** * Return element on top of heap but don't remove it. * * @return the element at top of heap * @throws NoSuchElementException if isEmpty() == true */ public synchronized Object peek() throws NoSuchElementException { return m_priorityQueue.peek(); } /** * Return element on top of heap and remove it. * * @return the element at top of heap * @throws NoSuchElementException if isEmpty() == true */ public synchronized Object pop() throws NoSuchElementException { return m_priorityQueue.pop(); } /** * Returns a string representation of the underlying queue. * * @return a string representation of the underlying queue */ public synchronized String toString() { return m_priorityQueue.toString(); } } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/Transformer.java0000644000175000017500000000414310777673521030500 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; /** * 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. * * @since Commons Collections 1.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author James Strachan * @author Stephen Colebourne */ 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 Object transform(Object input); } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/TransformerUtils.java0000644000175000017500000004540410777673522031527 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; import java.util.Collection; import java.util.Iterator; import java.util.Map; import org.apache.commons.collections.functors.ChainedTransformer; import org.apache.commons.collections.functors.CloneTransformer; import org.apache.commons.collections.functors.ClosureTransformer; import org.apache.commons.collections.functors.ConstantTransformer; import org.apache.commons.collections.functors.EqualPredicate; import org.apache.commons.collections.functors.ExceptionTransformer; import org.apache.commons.collections.functors.FactoryTransformer; import org.apache.commons.collections.functors.InstantiateTransformer; import org.apache.commons.collections.functors.InvokerTransformer; import org.apache.commons.collections.functors.MapTransformer; import org.apache.commons.collections.functors.NOPTransformer; import org.apache.commons.collections.functors.PredicateTransformer; import org.apache.commons.collections.functors.StringValueTransformer; import org.apache.commons.collections.functors.SwitchTransformer; /** * 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. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne * @author James Carman */ 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. * * @see org.apache.commons.collections.functors.ExceptionTransformer * * @return the transformer */ public static Transformer exceptionTransformer() { return ExceptionTransformer.INSTANCE; } /** * Gets a transformer that always returns null. * * @see org.apache.commons.collections.functors.ConstantTransformer * * @return the transformer */ 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). * * @see org.apache.commons.collections.functors.NOPTransformer * * @return the transformer */ 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 *
              * * @see org.apache.commons.collections.functors.CloneTransformer * * @return the transformer */ public static Transformer cloneTransformer() { return CloneTransformer.INSTANCE; } /** * Creates a Transformer that will return the same object each time the * transformer is used. * * @see org.apache.commons.collections.functors.ConstantTransformer * * @param constantToReturn the constant object to return each time in the transformer * @return the transformer. */ public static Transformer constantTransformer(Object constantToReturn) { return ConstantTransformer.getInstance(constantToReturn); } /** * Creates a Transformer that calls a Closure each time the transformer is used. * The transformer returns the input object. * * @see org.apache.commons.collections.functors.ClosureTransformer * * @param closure the closure to run each time in the transformer, not null * @return the transformer * @throws IllegalArgumentException if the closure is null */ 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. * * @see org.apache.commons.collections.functors.PredicateTransformer * * @param predicate the predicate to run each time in the transformer, not null * @return the transformer * @throws IllegalArgumentException if the predicate is null */ 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. * * @see org.apache.commons.collections.functors.FactoryTransformer * * @param factory the factory to run each time in the transformer, not null * @return the transformer * @throws IllegalArgumentException if the factory is null */ 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. * * @see org.apache.commons.collections.functors.ChainedTransformer * * @param transformer1 the first transformer * @param transformer2 the second transformer * @return the transformer * @throws IllegalArgumentException if either transformer is null */ 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. * * @see org.apache.commons.collections.functors.ChainedTransformer * * @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 */ 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. * * @see org.apache.commons.collections.functors.ChainedTransformer * * @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 */ 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. * * @see org.apache.commons.collections.functors.SwitchTransformer * * @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 */ 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. * * @see org.apache.commons.collections.functors.SwitchTransformer * * @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 */ 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. * * @see org.apache.commons.collections.functors.SwitchTransformer * * @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 */ 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. * * @see org.apache.commons.collections.functors.SwitchTransformer * * @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 */ public static Transformer switchTransformer(Map 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. * * @see org.apache.commons.collections.functors.SwitchTransformer * * @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 */ 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 = (Transformer) 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 = (Map.Entry) it.next(); preds[i] = EqualPredicate.getInstance(entry.getKey()); trs[i] = (Transformer) entry.getValue(); i++; } return switchTransformer(preds, trs, def); } /** * Gets a Transformer that expects an input Class object that it will instantiate. * * @see org.apache.commons.collections.functors.InstantiateTransformer * * @return the transformer */ 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. * * @see org.apache.commons.collections.functors.InstantiateTransformer * * @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 */ 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). * * @see org.apache.commons.collections.functors.MapTransformer * * @param map the map to use to transform the objects * @return the transformer * @throws IllegalArgumentException if the map is null */ 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. * * @see org.apache.commons.collections.functors.InvokerTransformer * * @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. */ 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. * * @see org.apache.commons.collections.functors.InvokerTransformer * * @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 */ 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'. * * @see org.apache.commons.collections.functors.StringValueTransformer * * @return the transformer */ public static Transformer stringValueTransformer() { return StringValueTransformer.INSTANCE; } } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/TreeBag.java0000644000175000017500000000462210777673521027511 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; import java.util.Collection; import java.util.Comparator; import java.util.SortedMap; import java.util.TreeMap; /** * A {@link Bag} that is backed by a {@link TreeMap}. * Order will be maintained among the unique representative * members. * * @deprecated Moved to bag subpackage and rewritten internally. Due to be removed in v4.0. * @since Commons Collections 2.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Chuck Burdick */ public class TreeBag extends DefaultMapBag implements SortedBag { /** * Constructs an empty TreeBag. */ public TreeBag() { super(new TreeMap()); } /** * Constructs an empty {@link 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 {@link Bag} containing all the members of the given * collection. * * @param coll the collection to copy into the bag */ public TreeBag(Collection coll) { this(); addAll(coll); } public Object first() { return ((SortedMap) getMap()).firstKey(); } public Object last() { return ((SortedMap) getMap()).lastKey(); } public Comparator comparator() { return ((SortedMap) getMap()).comparator(); } } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/UnboundedFifoBuffer.java0000644000175000017500000002011210777673521032051 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; 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. * * @deprecated Moved to buffer subpackage. Due to be removed in v4.0. * @since Commons Collections 2.1 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Avalon * @author Federico Barbieri * @author Berin Loritsch * @author Paul Jack * @author Stephen Colebourne * @author Andreas Schlosser */ public class UnboundedFifoBuffer extends AbstractCollection implements Buffer { protected Object[] m_buffer; protected int m_head; protected int m_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"); } m_buffer = new Object[initialSize + 1]; m_head = 0; m_tail = 0; } /** * Returns the number of elements stored in the buffer. * * @return this buffer's size */ public int size() { int size = 0; if (m_tail < m_head) { size = m_buffer.length - m_head + m_tail; } else { size = m_tail - m_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 * @throws BufferOverflowException if this buffer is full */ public boolean add(final Object obj) { if (obj == null) { throw new NullPointerException("Attempted to add null object to buffer"); } if (size() + 1 >= m_buffer.length) { Object[] tmp = new Object[((m_buffer.length - 1) * 2) + 1]; int j = 0; for (int i = m_head; i != m_tail;) { tmp[j] = m_buffer[i]; m_buffer[i] = null; j++; i++; if (i == m_buffer.length) { i = 0; } } m_buffer = tmp; m_head = 0; m_tail = j; } m_buffer[m_tail] = obj; m_tail++; if (m_tail >= m_buffer.length) { m_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 Object get() { if (isEmpty()) { throw new BufferUnderflowException("The buffer is already empty"); } return m_buffer[m_head]; } /** * Removes the next object from the buffer * * @return the removed object * @throws BufferUnderflowException if this buffer is empty */ public Object remove() { if (isEmpty()) { throw new BufferUnderflowException("The buffer is already empty"); } Object element = m_buffer[m_head]; if (null != element) { m_buffer[m_head] = null; m_head++; if (m_head >= m_buffer.length) { m_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 >= m_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 = m_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 = m_head; private int lastReturnedIndex = -1; public boolean hasNext() { return index != m_tail; } public Object next() { if (!hasNext()) throw new NoSuchElementException(); lastReturnedIndex = index; index = increment(index); return m_buffer[lastReturnedIndex]; } public void remove() { if (lastReturnedIndex == -1) throw new IllegalStateException(); // First element can be removed quickly if (lastReturnedIndex == m_head) { UnboundedFifoBuffer.this.remove(); lastReturnedIndex = -1; return; } // Other elements require us to shift the subsequent elements int i = increment(lastReturnedIndex); while (i != m_tail) { m_buffer[decrement(i)] = m_buffer[i]; i = increment(i); } lastReturnedIndex = -1; m_tail = decrement(m_tail); m_buffer[m_tail] = null; index = decrement(index); } }; } } libcommons-collections3-java.orig/src/java/org/apache/commons/collections/Unmodifiable.java0000644000175000017500000000310610777673521030572 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; /** * Marker interface for collections, 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. * * @since Commons Collections 3.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ public interface Unmodifiable { // marker interface - no methods to implement } libcommons-collections3-java.orig/src/media/0000755000175000017500000000000011010124151017431 5ustar godgodlibcommons-collections3-java.orig/src/media/logo.xcf0000644000175000017500000006002410777673306021133 0ustar godgodgimp 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% libcommons-collections3-java.orig/src/site/0000755000175000017500000000000011010124151017316 5ustar godgodlibcommons-collections3-java.orig/src/site/resources/0000755000175000017500000000000010777673522021366 5ustar godgodlibcommons-collections3-java.orig/src/site/resources/images/0000755000175000017500000000000011010124151022575 5ustar godgodlibcommons-collections3-java.orig/src/site/resources/images/logo.png0000644000175000017500000003276110777673522024312 0ustar godgodPNG  IHDR,dcbKGD pHYs  ~tIME "ns IDATx}{X~.珎'.`S0NI%@@/XcbYE3I4oǻ%)~s,AABDo\2c}[aY{Y{ޯ 2s\q$v.rQW']&]&]&]&]&]&]&]&]&]&]&]&݋akKiDoᷳkػ7od wv)//ĉyyy𸿿` `AoʲQpPHL&SfffxxxXXbb"'Jv9FҥKZZZP&%%ݺuڪ,99ٮ5(77ni7;v 5l˰'NHNNFͥfͲenݢ]fWClBBBBB11~˱n3g[___[[{Çغuk}}[L5c *>ҶmР?Ѹl2RZZZ]]]}}}RRG yf]]ݭ[[1Td]p}.-\Z j:u*2_h42aaa uuu555[l G̑#G V[[W_mٲn|Mcc#t}MM͑#GBCCQNmmm]]vrص/^qիW嗪Оظq7\lm߾eXbbb7oRi$%''9R Ϝ9듒Ҷl2uTwީںu+7!!!==}۶m7o2eNS3߼yq>rH56l`0| cի#F`}[nڴ)66.smm[~IdBBB]]͛7]V]]M}\p9r]î_~ԴiӶm۶u֩Srtڵk_1h;v પׯթt&r @^___ƍJ\;C{׷իQc,--UUUTdcbbkjjX֖ ڳgOuu5xb1LVbŝ?Auul.++;qℯ/e.--X,7nhllX`Ztx嗋^ :yQ_|Z6)//rʕ+9沲Z/F#"0>>͛jΰk֬0s.0v577s悦:u_~,//|r`` \rdާ!`0ԀfbTVVVUUUUU۷xʌFb~zCCC' 5xԔ炂 c(j4F֭[OիO> ( TThh;-N0GGGܹ/\C=#!hCpp|?O? :t,NVkkkkkkkϜ9J۷/22rڵ=ztMo H1?ѽ{ҥK'NأGƘ$I jdeea~UV=sVw|bf555\[[[VVQ裏^}=zAIIzVuȐ!ĦCCC@ChV u:/\0}tp V+45 >L>gϞh;F?r/ihhKٳg_'O3I@B\{544ѯ_ 2vZoŠ'z-*C(1x-:s̙O=L <iO?tcc#mb*eyٲe ߧ9}?-4 QXѸҬCG0T2??*2%!91NmD퀐ntt4v?E n۶m/^gϞtu+77fC ill.EÖ<==H}b]z}E*$Iݻw8p .ۭ[75ÇqC :hZٳ ְ|Ѳ|rdM M8}.b2\0ʖ̡|ڵ O-}777VYG?J0;;?ۗC;,C={~:Jpp0s( rtnu4bũݺuw1e MKEř10tww80B3NJ0P2ƞx XPÂm=<<+W`S7  dii@YpMIAɣGBdwssvb(:hık t)3 H@ gdooo@S* &v}G$ #`nrw_n<<`DsM$>]`ddupYC^^+BmێX,@qޮԆmKI$>%%%..c>}O<_tI=Q#!2% S Ni:\\Y&*rӁ@L]CmW& (H VgYl pK>,l;(iii'OVudȐ -w6滇uC8ѣmM8Q7O<}E\qZ Ha; 0l۾+_9zKN;kw;!c\p svү_?v;@ VQ]V\Ezo9rdl6'\ Aġ#Ջc"'++kԨQ4r.))AQ݅ @E"(]\QYYYYY)jAj؀//GNMMB?rʏ>۷ ;q^s-//Uv5jԧ~J]ٳg 6x`,wk')44&+fkۡCrl*ѼG'N iQk ۙr[)))eeeX?c@`xxxHH- 6= mr^x1N 1AMFꫯFd F__q Zݓ,YYY4=-! SLԶN@(Œ3#G3&//CԲeÍFczz:҂ഴ4*jΝf+ 98teS!t=RYY}vn7-2"5ݲ_RSSBV¾O>ٷo_Z)A8Zh'Œп9sdddddddff&''?pX)==ˋ6oLE8ZB U_(n۶8Y|yyy9An0Au`I_B`V\y:a_z9!I:3i&_+**֬Y3a„c>s˗/l۶-::O~+:pEPIIɬYh-(L^߻w< 22ܼ9=p Ree3vcFJ>xA &FFAy8q'rkk[?pbӧO2e fnmm{EEEڨFUUUgggsǩPȄG}SՎ3d2X={0t:]HH=_}I&MpV m<==xݦN}.]!弽"""0Va£ܘ0L*t?Þ:uテRь1`0t:XZJ$Q!Zc~x<ԩS zj, =.k0fΜ ̐\!3 d0pkbXj7oܽ{wwwqơX*1O:rww"Lיyڴi ¤-+++**:t \N躻\Oo޼[n+V~BdL2h ɓ'}||?¥REEEUUU%%%fNu >"oKK c AKoF uwaыJC~8s(:P]__T6wjL ,IFf |$&$aelO28f0X02p!2Sɨo tI<==AOaC`LE*hjBsИt5)vhЗ:뙦E!(Gᘹy+R)(E 5Om t"( O19+KA  q02%z@(B]`bE#nK %DBx& KBT8 JPhWOӠ'= =S9J jR$G{;ЩP` X";;a-,, ijUޥwqx:233?Ao" Vuڴiǎ۹s'=(ܚٯ5d2|IAfϞcq{i z|%5P`` ѷ51^-3`ʃsK22%''C`jjjjjd~ r^!D w>^M_UÆ Xefw$Z}KwGhhm] ]Ƃ#7"qqq&2-W}x,8hEރ !mOZbw\ln!LpHmvik$K2wN:l ^g$ٳTWE|rN_; ˾8 tB~HAAAih*Ld\g[ Җ⢮`Kw3eNY,& /ILLt[z9x \AK'K𡠠(V +1,S+PuЮ0^o˗sWԔeggø'؞TwG3jA9>}d2L&D}d2egg߮AgA`oVӡ>?cGXXرcDYYY.xѣM&V5Q5XXv,˲|ĉp0DZҥK`x_o;\C_t)pΚ5 ojj—p /%d̙)ʕ+.\8w\IIɹs.\p劊 .^ߟ={ٳ?åK˫kjjbO?Qg͚;ⴲZW\5kcɒ%!/Qǎ۱cǎ;Qϸׯ[n͚5999/_6111pآEn޼yk׮]zڵk7nܨ{khɒ%koFz[ŋq1T__44NFF$&&M~gux{p~),䫯K._U;wG1$@777#OHHHEEEii?xܹg~?SYYb:u*SXXX={s~˗/k׮]x]۾};ʩA,^gxCC*<}t4 ťK.\?^p.++3G~U]vZe -@ϤӧOOKK<Çqƍ7n޼ ǀJKK& jBp?(5j sxrYYY=0;v1b}> wrIDATrrrrh50F0`l(tBå4sx2O4PNZeff1cFcBBŽ;lT-+"X4 mۭ?K'팃Opp/^ZBLw Ik„ 1^xb|E[lpsrrÆ k}5\$Ii?88^Qhdh>Sۙ U쌄o??777 AAA֭.,++C!QQQ7oKFTTSDR . e˖z}JJ g dY~wc^^^Vrjyy9z`:u*M3l2PQV+]aذap'Zٽ{76=_E m0^}U./T`c-Hո8p\Y#ŠlF0f{%mDž L&󫯾Vi];ch4Xi/Kb V#ׯ V\jFh0 ,3'uUͅ0ƒYɈAnҶlقΊKjs@IӧOXXxdm۶ ޽{͚55k<ݤ7_CCC$U 6@@#З_~ʒr{7}Ȑ!ȳuV._?93~AA%::?/,,hjjȖIaa!j޳gOPklqqq>9XAAyz-+3''jTAVTEA(2"^~@$rڑf֭:u*[%u5YWPMp6H'!!!~x`{wQڴiӼLwށbtիWC)8xɆ *** $-02'MNz2%!`+)F΍7:hvVxMHFFLPnX-**GDD*[|H^Vkppphh( \n  2O#ÞRSa^^nB1GJq"n#磴ixI+c,22[W]Bո bYv-J3AVuڵ6l0͌I&[@Ԇ Y52# #Qxo+jÿ6 ~Ū\'-IREE3 ˈU 7::zʔ)s}q> }Ms\+%Iڼy?ӦM믽Pԑ +Pe|E&S {FbeY޻w/>>`pVʊ;\ܟhjBH+K!וڵk 'FGG"0N ~@)clذa4Udx[`AAu7hE[^v hl*VXX3~x\dYmX___ooot7o~{.--F-m~sW!-O 7vK~6gUݠƂ!AjsӑPx<5q~|||lؿ?>KBLbhN 7q_oFNN@# cJ^MAvfsFFZag}G0+7bpX,)))p:lqBQ=$v9ʲLחuf>/:|,Igi~oa:j6qjl޺(7!zcl6;Y[[[*t]Y@\±Q=w91UJFSTTXFtPƄ g i|ypdJ;t9:db@ ^|E>\\\ 3m|{,RWܬZm19 p2`߂.32Y,:-CÅDdBv' hU]Ӧ^ND8QWqU}g FͮK 3-H!;x z'00Iw}OVGj B0>А/>7my([~=N-Ps= ,;.\Bb8+qI~uQԪXttl{lx ngsdd}M 6m~~~&MBGZ.BjF\]44qȻ(Vo6m 8FGG#-˸qtcǎT'9\"f?xgiYn|@@mXe̙3x 8-rĥyڙ晑\!`())ݻL3yd:>Y] ` Z/_R?"رcWXANoȖI!E tϼy-[}II Z'IK.]#!$Iv{::ׯ_ Z{h~ZPKeY6)))qS810T굨v,b722َ0oHxAO%VjRFeU1XŌ-RZ knܸ[`J$-z>12!F!oݺ5..04 /~ר|Ԗ$i,c=#@3f̰;>oٲ%>>~7nąJÇSpMCy7wl3 8Dcccnjc+4@ž{Z}6Kl1#(^,\,vEM`06S, l3v d (CQ%fhBEHB@Bf[VW$cב_"e%(BxMPۣn4M͘QEQt:pÊlXjw w۸B8_0^L+LGdCf;g%UEP j=Sk8b tFe)@6D1c]@YWBc@ڈ\cJ=d̡?JLTNR^_Wh(89%Lq2LSqfAԈE5héz_n@ж\f ?5ۈ)sIV]W'sП85*@0pn9.2?9Ȭ椒Wv*1*ܒ,+ jI#ǹVsuAl 4]r8!GgmdA@ȈpZq]_8h'Yma'l(9XT3m5ߕAd캚qvЮh ?8 NK4Nvî>gB j.?;~.C@vmkSY;`vFNj~2Bé'trE.`rE.`rE.`rE.`rE.`rE.`2!IENDB`libcommons-collections3-java.orig/src/site/site.xml0000644000175000017500000000402110777673522021037 0ustar godgod Commons Collections /images/logo.png /index.html libcommons-collections3-java.orig/src/test/0000755000175000017500000000000010777673306017367 5ustar godgodlibcommons-collections3-java.orig/src/test/org/0000755000175000017500000000000010777673306020156 5ustar godgodlibcommons-collections3-java.orig/src/test/org/apache/0000755000175000017500000000000010777673306021377 5ustar godgodlibcommons-collections3-java.orig/src/test/org/apache/commons/0000755000175000017500000000000010777673306023052 5ustar godgodlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/0000755000175000017500000000000011010124151025332 5ustar godgodlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/bag/0000755000175000017500000000000011010124151026063 5ustar godgodlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/bag/AbstractTestBag.java0000644000175000017500000004434410777673306032012 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.bag; import java.io.IOException; import java.io.Serializable; import java.util.ArrayList; import java.util.ConcurrentModificationException; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import org.apache.commons.collections.AbstractTestObject; import org.apache.commons.collections.Bag; /** * Abstract test class for {@link org.apache.commons.collections.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. * * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Chuck Burdick * @author Stephen Colebourne */ 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 testIteratorRemoveProtectsInvariants() { Bag bag = makeBag(); bag.add("A"); bag.add("A"); assertEquals(2, bag.size()); Iterator it = bag.iterator(); assertEquals("A", it.next()); assertEquals(true, it.hasNext()); it.remove(); assertEquals(1, bag.size()); assertEquals(true, it.hasNext()); assertEquals("A", it.next()); assertEquals(false, it.hasNext()); it.remove(); assertEquals(0, bag.size()); assertEquals(false, it.hasNext()); Iterator it2 = bag.iterator(); assertEquals(false, it2.hasNext()); } 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 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 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); } } } ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/bag/AbstractTestSortedBag.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/bag/AbstractTestSortedBag.0000644000175000017500000000253610777673306032326 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.bag; /** * Abstract test class for * {@link org.apache.commons.collections.SortedBag SortedBag} * methods and contracts. * * @since Commons Collections 3.0 * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ public abstract class AbstractTestSortedBag extends AbstractTestBag { public AbstractTestSortedBag(String testName) { super(testName); } // TODO: Add the SortedBag tests! } libcommons-collections3-java.orig/src/test/org/apache/commons/collections/bag/TestAll.java0000644000175000017500000000374410777673306030344 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.bag; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * Entry point for tests. * * @since Commons Collections 3.0 * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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; } } libcommons-collections3-java.orig/src/test/org/apache/commons/collections/bag/TestHashBag.java0000644000175000017500000000432610777673306031126 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.bag; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.collections.Bag; /** * Extension of {@link TestBag} for exercising the {@link HashBag} * implementation. * * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Chuck Burdick */ 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/collections/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/collections/data/test/HashBag.fullCollection.version3.obj"); // } } ././@LongLink0000000000000000000000000000014500000000000011565 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/bag/TestPredicatedBag.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/bag/TestPredicatedBag.java0000644000175000017500000001172110777673307032305 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.bag; import java.util.Set; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.collections.Bag; import org.apache.commons.collections.Predicate; import org.apache.commons.collections.PredicateUtils; /** * Extension of {@link TestBag} for exercising the {@link PredicatedBag} * implementation. * * @since Commons Collections 3.0 * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Phil Steitz */ 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/collections/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/collections/data/test/PredicatedBag.fullCollection.version3.1.obj"); // } } ././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/bag/TestPredicatedSortedBag.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/bag/TestPredicatedSortedBa0000644000175000017500000001065110777673306032377 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.bag; import java.util.Comparator; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.collections.Bag; import org.apache.commons.collections.Predicate; import org.apache.commons.collections.PredicateUtils; import org.apache.commons.collections.SortedBag; /** * Extension of {@link TestBag} for exercising the {@link PredicatedSortedBag} * implementation. * * @since Commons Collections 3.0 * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Phil Steitz */ 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/collections/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/collections/data/test/PredicatedSortedBag.fullCollection.version3.1.obj"); // } } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/bag/TestTransformedBag.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/bag/TestTransformedBag.jav0000644000175000017500000000617710777673307032375 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.bag; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.collections.Bag; import org.apache.commons.collections.collection.TestTransformedCollection; /** * Extension of {@link TestBag} for exercising the {@link TransformedBag} * implementation. * * @since Commons Collections 3.0 * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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/collections/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/collections/data/test/TransformedBag.fullCollection.version3.1.obj"); // } } ././@LongLink0000000000000000000000000000015400000000000011565 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/bag/TestTransformedSortedBag.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/bag/TestTransformedSortedB0000644000175000017500000000612710777673306032461 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.bag; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.collections.Bag; import org.apache.commons.collections.collection.TestTransformedCollection; /** * Extension of {@link TestSortedBag} for exercising the {@link TransformedSortedBag} * implementation. * * @since Commons Collections 3.0 * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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/collections/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/collections/data/test/TransformedSortedBag.fullCollection.version3.1.obj"); // } } libcommons-collections3-java.orig/src/test/org/apache/commons/collections/bag/TestTreeBag.java0000644000175000017500000000574210777673306031145 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.bag; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.collections.Bag; import org.apache.commons.collections.SortedBag; /** * Extension of {@link TestBag} for exercising the {@link TreeBag} * implementation. * * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Chuck Burdick */ 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/collections/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/collections/data/test/TreeBag.fullCollection.version3.obj"); // } } libcommons-collections3-java.orig/src/test/org/apache/commons/collections/bag/TestTypedBag.java0000644000175000017500000001023010777673306031317 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.bag; import java.util.Set; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.collections.Bag; /** * Extension of {@link TestBag} for exercising the {@link TypedBag} * implementation. * * @since Commons Collections 3.0 * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Phil Steitz */ 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; } } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/bag/TestTypedSortedBag.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/bag/TestTypedSortedBag.jav0000644000175000017500000000702310777673306032345 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.bag; import java.util.Comparator; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.collections.Bag; import org.apache.commons.collections.SortedBag; /** * Extension of {@link TestBag} for exercising the {@link TypedSortedBag} * implementation. * * @since Commons Collections 3.0 * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Phil Steitz */ 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; } } libcommons-collections3-java.orig/src/test/org/apache/commons/collections/bidimap/0000755000175000017500000000000011010124151026737 5ustar godgod././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/bidimap/AbstractTestBidiMap.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/bidimap/AbstractTestBidiMa0000644000175000017500000005216510777673434032404 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.bidimap; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; import org.apache.commons.collections.BidiMap; import org.apache.commons.collections.BulkTest; import org.apache.commons.collections.MapIterator; import org.apache.commons.collections.iterators.AbstractTestMapIterator; import org.apache.commons.collections.map.AbstractTestMap; /** * Abstract test class for {@link BidiMap} methods and contracts. * * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Matthew Hawthorne * @author Stephen Colebourne */ 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(); } } } ././@LongLink0000000000000000000000000000016200000000000011564 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/bidimap/AbstractTestOrderedBidiMap.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/bidimap/AbstractTestOrdere0000644000175000017500000001551710777673435032500 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.bidimap; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import org.apache.commons.collections.BulkTest; import org.apache.commons.collections.MapIterator; import org.apache.commons.collections.OrderedBidiMap; import org.apache.commons.collections.iterators.AbstractTestMapIterator; /** * Abstract test class for {@link OrderedBidiMap} methods and contracts. * * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Matthew Hawthorne * @author Stephen Colebourne */ 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(); } } } ././@LongLink0000000000000000000000000000016100000000000011563 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/bidimap/AbstractTestSortedBidiMap.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/bidimap/AbstractTestSorted0000644000175000017500000006750310777673435032522 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.bidimap; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.SortedMap; import java.util.SortedSet; import java.util.TreeMap; import java.util.TreeSet; import org.apache.commons.collections.BulkTest; import org.apache.commons.collections.SortedBidiMap; import org.apache.commons.collections.map.AbstractTestSortedMap; /** * Abstract test class for {@link SortedBidiMap} methods and contracts. * * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Matthew Hawthorne * @author Stephen Colebourne */ 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); } } ././@LongLink0000000000000000000000000000017300000000000011566 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/bidimap/TestAbstractOrderedBidiMapDecorator.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/bidimap/TestAbstractOrdere0000644000175000017500000000516010777673434032470 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.bidimap; import java.util.Map; import java.util.TreeMap; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.collections.BidiMap; import org.apache.commons.collections.OrderedBidiMap; /** * Test class for AbstractOrderedBidiMapDecorator. * * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ */ 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; } } } libcommons-collections3-java.orig/src/test/org/apache/commons/collections/bidimap/TestAll.java0000644000175000017500000000405210777673434031213 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.bidimap; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * Entry point for tests. * * @since Commons Collections 3.0 * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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; } } ././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/bidimap/TestDualHashBidiMap.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/bidimap/TestDualHashBidiMa0000644000175000017500000000433110777673434032322 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.bidimap; import junit.framework.Test; import junit.textui.TestRunner; import org.apache.commons.collections.BidiMap; import org.apache.commons.collections.BulkTest; /** * JUnit tests. * * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Matthew Hawthorne * @author Stephen Colebourne */ 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/collections/data/test/DualHashBidiMap.emptyCollection.version3.obj"); // resetFull(); // writeExternalFormToDisk((Serializable) map, "D:/dev/collections/data/test/DualHashBidiMap.fullCollection.version3.obj"); // } } ././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/bidimap/TestDualTreeBidiMap.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/bidimap/TestDualTreeBidiMa0000644000175000017500000000433710777673435032345 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.bidimap; import junit.framework.Test; import junit.textui.TestRunner; import org.apache.commons.collections.BidiMap; import org.apache.commons.collections.BulkTest; /** * JUnit tests. * * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Matthew Hawthorne * @author Stephen Colebourne */ 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/collections/data/test/DualTreeBidiMap.emptyCollection.version3.obj"); // resetFull(); // writeExternalFormToDisk((Serializable) map, "D:/dev/collections/data/test/DualTreeBidiMap.fullCollection.version3.obj"); // } } ././@LongLink0000000000000000000000000000015400000000000011565 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/bidimap/TestDualTreeBidiMap2.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/bidimap/TestDualTreeBidiMa0000644000175000017500000001203610777673435032340 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.bidimap; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.TreeMap; import junit.framework.Test; import junit.textui.TestRunner; import org.apache.commons.collections.BidiMap; import org.apache.commons.collections.BulkTest; import org.apache.commons.collections.SortedBidiMap; import org.apache.commons.collections.comparators.ComparableComparator; import org.apache.commons.collections.comparators.ReverseComparator; /** * JUnit tests. * * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Matthew Hawthorne * @author Stephen Colebourne * @author Jonas Van Poucke */ 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 new DualTreeBidiMap(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/collections/data/test/DualTreeBidiMap.emptyCollection.version3.Test2.obj"); // resetFull(); // writeExternalFormToDisk((java.io.Serializable) map, "D:/dev/collections/data/test/DualTreeBidiMap.fullCollection.version3.Test2.obj"); // } } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/bidimap/TestTreeBidiMap.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/bidimap/TestTreeBidiMap.ja0000644000175000017500000000424510777673434032305 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.bidimap; import java.util.Map; import java.util.TreeMap; import junit.framework.Test; import junit.textui.TestRunner; import org.apache.commons.collections.BidiMap; import org.apache.commons.collections.BulkTest; /** * JUnit tests. * * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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; } } ././@LongLink0000000000000000000000000000015700000000000011570 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/bidimap/TestUnmodifiableBidiMap.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/bidimap/TestUnmodifiableBi0000644000175000017500000000520710777673434032437 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.bidimap; import java.util.HashMap; import java.util.Map; import junit.framework.Test; import junit.textui.TestRunner; import org.apache.commons.collections.BidiMap; import org.apache.commons.collections.BulkTest; /** * JUnit tests. * * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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; } } ././@LongLink0000000000000000000000000000016600000000000011570 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/bidimap/TestUnmodifiableOrderedBidiMap.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/bidimap/TestUnmodifiableOr0000644000175000017500000000561010777673435032464 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.bidimap; import java.util.Map; import java.util.TreeMap; import junit.framework.Test; import junit.textui.TestRunner; import org.apache.commons.collections.BidiMap; import org.apache.commons.collections.BulkTest; import org.apache.commons.collections.OrderedBidiMap; /** * JUnit tests. * * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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; } } ././@LongLink0000000000000000000000000000016500000000000011567 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/bidimap/TestUnmodifiableSortedBidiMap.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/bidimap/TestUnmodifiableSo0000644000175000017500000000624610777673434032472 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.bidimap; import java.util.Map; import java.util.TreeMap; import junit.framework.Test; import junit.textui.TestRunner; import org.apache.commons.collections.BidiMap; import org.apache.commons.collections.BulkTest; import org.apache.commons.collections.SortedBidiMap; /** * JUnit tests. * * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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; } } libcommons-collections3-java.orig/src/test/org/apache/commons/collections/buffer/0000755000175000017500000000000011010124151026603 5ustar godgodlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/buffer/TestAll.java0000644000175000017500000000425110777673322031054 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.buffer; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * Entry point for tests. * * @since Commons Collections 3.0 * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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(TestBoundedBuffer.suite()); suite.addTest(TestPredicatedBuffer.suite()); suite.addTest(TestSynchronizedBuffer.suite()); suite.addTest(TestTransformedBuffer.suite()); suite.addTest(TestUnmodifiableBuffer.suite()); return suite; } } ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/buffer/TestBlockingBuffer.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/buffer/TestBlockingBuffer.0000644000175000017500000004726610777673322032401 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.buffer; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.collections.AbstractTestObject; import org.apache.commons.collections.Buffer; import org.apache.commons.collections.BufferUnderflowException; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.LinkedList; import java.util.Set; /** * Extension of {@link AbstractTestObject} for exercising the {@link BlockingBuffer} implementation. * * @author Janek Bogucki * @author Phil Steitz * @version $Revision: 646780 $ * @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(Object)}. */ 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() ); } public void testGetWithAddTimeout() { Buffer blockingBuffer = BlockingBuffer.decorate( new MyBuffer(), 500 ); Object obj = new Object(); new DelayedAdd( blockingBuffer, obj, 100 ).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(java.util.Collection)}. */ 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() ); } public void testGetWithAddAllTimeout() { Buffer blockingBuffer = BlockingBuffer.decorate( new MyBuffer(), 500 ); Object obj = new Object(); new DelayedAddAll( blockingBuffer, obj, 100 ).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(Object)}. */ 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() ); } public void testRemoveWithAddTimeout() { Buffer blockingBuffer = BlockingBuffer.decorate( new MyBuffer(), 100 ); Object obj = new Object(); new DelayedAdd( blockingBuffer, obj, 500 ).start(); try { blockingBuffer.remove(); } catch( BufferUnderflowException e ) { } } //----------------------------------------------------------------------- /** * Tests {@link BlockingBuffer#remove()} in combination with {@link BlockingBuffer#addAll(java.util.Collection)}. */ 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() ); } public void testRemoveWithAddAllTimeout() { Buffer blockingBuffer = BlockingBuffer.decorate( new MyBuffer(), 100 ); Object obj = new Object(); new DelayedAddAll( blockingBuffer, obj, 500 ).start(); try { blockingBuffer.remove(); } catch( BufferUnderflowException e ) { } } //----------------------------------------------------------------------- /** * Tests {@link BlockingBuffer#get()} in combination with {@link BlockingBuffer#add(Object)} 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(java.util.Collection)} 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(Object)} 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(java.util.Collection)} * 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(java.util.Collection)} * 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." ); } } public void testTimeoutGet() { final BlockingBuffer buffer = new BlockingBuffer( new MyBuffer() ); try { buffer.get( 100 ); fail( "Get should have timed out." ); } catch( BufferUnderflowException e ) { } } public void testTimeoutRemove() { final BlockingBuffer buffer = new BlockingBuffer( new MyBuffer() ); try { buffer.remove( 100 ); fail( "Get should have timed out." ); } catch( BufferUnderflowException e ) { } } protected static class DelayedAdd extends Thread { Buffer buffer; Object obj; long delay = 1000; public DelayedAdd( Buffer buffer, Object obj, long delay ) { this.buffer = buffer; this.obj = obj; this.delay = delay; } 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.sleep( delay ); } catch( InterruptedException e ) { } buffer.add( obj ); } } protected static class DelayedAddAll extends Thread { Buffer buffer; Object obj; long delay = 100; public DelayedAddAll( Buffer buffer, Object obj, long delay ) { this.buffer = buffer; this.obj = obj; this.delay = delay; } 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.sleep( delay ); } 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.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/collections/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/collections/data/test/BlockingBuffer.fullCollection.version3.1.obj"); // } } ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/buffer/TestBoundedBuffer.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/buffer/TestBoundedBuffer.j0000644000175000017500000001632010777673322032366 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.buffer; import org.apache.commons.collections.AbstractTestObject; import org.apache.commons.collections.BoundedCollection; import org.apache.commons.collections.Buffer; import org.apache.commons.collections.BufferOverflowException; import java.util.Iterator; import java.util.Collections; import java.util.Arrays; import junit.framework.Test; import junit.framework.TestSuite; public class TestBoundedBuffer extends AbstractTestObject { public TestBoundedBuffer(String testName) { super(testName); } public static Test suite() { return new TestSuite(TestBoundedBuffer.class); } public static void main(String args[]) { String[] testCaseName = { TestBoundedBuffer.class.getName() }; junit.textui.TestRunner.main(testCaseName); } public String getCompatibilityVersion() { return "3.2"; } public boolean isEqualsCheckable() { return false; } public Object makeObject() { return BoundedBuffer.decorate(new UnboundedFifoBuffer(), 1); } //----------------------------------------------------------------------- public void testMaxSize() { final Buffer bounded = BoundedBuffer.decorate(new UnboundedFifoBuffer(), 2, 500); BoundedCollection bc = (BoundedCollection) bounded; assertEquals(2, bc.maxSize()); assertEquals(false, bc.isFull()); bounded.add("A"); assertEquals(false, bc.isFull()); bounded.add("B"); assertEquals(true, bc.isFull()); bounded.remove(); assertEquals(false, bc.isFull()); try { BoundedBuffer.decorate(new UnboundedFifoBuffer(), 0); fail(); } catch (IllegalArgumentException ex) {} try { BoundedBuffer.decorate(new UnboundedFifoBuffer(), -1); fail(); } catch (IllegalArgumentException ex) {} } public void testAddToFullBufferNoTimeout() { final Buffer bounded = BoundedBuffer.decorate(new UnboundedFifoBuffer(), 1); bounded.add( "Hello" ); try { bounded.add("World"); fail(); } catch (BufferOverflowException e) { } } public void testAddAllToFullBufferNoTimeout() { final Buffer bounded = BoundedBuffer.decorate(new UnboundedFifoBuffer(), 1); bounded.add( "Hello" ); try { bounded.addAll(Collections.singleton("World")); fail(); } catch (BufferOverflowException e) { } } public void testAddAllToEmptyBufferExceedMaxSizeNoTimeout() { final Buffer bounded = BoundedBuffer.decorate(new UnboundedFifoBuffer(), 1); try { bounded.addAll(Collections.nCopies(2, "test")); fail(); } catch (BufferOverflowException e) { } } public void testAddToFullBufferRemoveViaIterator() { final Buffer bounded = BoundedBuffer.decorate(new UnboundedFifoBuffer(), 1, 500); bounded.add( "Hello" ); new DelayedIteratorRemove( bounded, 200 ).start(); bounded.add( "World" ); assertEquals( 1, bounded.size() ); assertEquals( "World", bounded.get() ); } public void testAddAllToFullBufferRemoveViaIterator() { final Buffer bounded = BoundedBuffer.decorate(new UnboundedFifoBuffer(), 2, 500); bounded.add( "Hello" ); bounded.add( "World" ); new DelayedIteratorRemove( bounded, 200, 2 ).start(); bounded.addAll( Arrays.asList( new String[] { "Foo", "Bar" } ) ); assertEquals( 2, bounded.size() ); assertEquals( "Foo", bounded.remove() ); assertEquals( "Bar", bounded.remove() ); } public void testAddToFullBufferWithTimeout() { final Buffer bounded = BoundedBuffer.decorate(new UnboundedFifoBuffer(), 1, 500); bounded.add( "Hello" ); new DelayedRemove( bounded, 200 ).start(); bounded.add( "World" ); assertEquals( 1, bounded.size() ); assertEquals( "World", bounded.get() ); try { bounded.add( "!" ); fail(); } catch( BufferOverflowException e ) { } } public void testAddAllToFullBufferWithTimeout() { final Buffer bounded = BoundedBuffer.decorate(new UnboundedFifoBuffer(), 2, 500); bounded.add( "Hello" ); bounded.add( "World" ); new DelayedRemove( bounded, 200, 2 ).start(); bounded.addAll( Arrays.asList( new String[] { "Foo", "Bar" } ) ); assertEquals( 2, bounded.size() ); assertEquals( "Foo", bounded.get() ); try { bounded.add( "!" ); fail(); } catch( BufferOverflowException e ) { } } private class DelayedIteratorRemove extends Thread { private final Buffer buffer; private final long delay; private final int nToRemove; public DelayedIteratorRemove(Buffer buffer, long delay, int nToRemove) { this.buffer = buffer; this.delay = delay; this.nToRemove = nToRemove; } public DelayedIteratorRemove(Buffer buffer, long delay) { this(buffer, delay, 1); } public void run() { try { Thread.sleep(delay); Iterator iter = buffer.iterator(); for (int i = 0; i < nToRemove; ++i) { iter.next(); iter.remove(); } } catch (InterruptedException e) { } } } private class DelayedRemove extends Thread { private final Buffer buffer; private final long delay; private final int nToRemove; public DelayedRemove(Buffer buffer, long delay, int nToRemove) { this.buffer = buffer; this.delay = delay; this.nToRemove = nToRemove; } public DelayedRemove(Buffer buffer, long delay) { this(buffer, delay, 1); } public void run() { try { Thread.sleep(delay); for (int i = 0; i < nToRemove; ++i) { buffer.remove(); } } catch (InterruptedException e) { } } } }././@LongLink0000000000000000000000000000015400000000000011565 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/buffer/TestBoundedFifoBuffer.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/buffer/TestBoundedFifoBuff0000644000175000017500000001353610777673322032421 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.buffer; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import junit.framework.Test; import org.apache.commons.collections.BufferUnderflowException; import org.apache.commons.collections.BulkTest; import org.apache.commons.collections.collection.AbstractTestCollection; /** * Test cases for BoundedFifoBuffer. * * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Paul Jack */ 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"; } // BZ 33071 -- gets start=end=1 before removal of interior element public void testShift() { BoundedFifoBuffer fifo = new BoundedFifoBuffer(3); fifo.add("a"); fifo.add("b"); fifo.add("c"); fifo.remove(); fifo.add("e"); fifo.remove("c"); } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk((java.io.Serializable) collection, "D:/dev/collections/data/test/BoundedFifoBuffer.emptyCollection.version3.1.obj"); // resetFull(); // writeExternalFormToDisk((java.io.Serializable) collection, "D:/dev/collections/data/test/BoundedFifoBuffer.fullCollection.version3.1.obj"); // } } ././@LongLink0000000000000000000000000000015500000000000011566 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/buffer/TestBoundedFifoBuffer2.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/buffer/TestBoundedFifoBuff0000644000175000017500000000764710777673322032427 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.buffer; import java.util.Arrays; import java.util.Collection; import junit.framework.Test; import org.apache.commons.collections.BoundedCollection; import org.apache.commons.collections.BufferOverflowException; import org.apache.commons.collections.BulkTest; /** * Runs tests against a full BoundedFifoBuffer, since many of the algorithms * differ depending on whether the fifo is full or not. * * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Unknown */ 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()); } } ././@LongLink0000000000000000000000000000015500000000000011566 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/buffer/TestCircularFifoBuffer.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/buffer/TestCircularFifoBuf0000644000175000017500000003241410777673322032433 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.buffer; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import junit.framework.Test; import junit.textui.TestRunner; import org.apache.commons.collections.Buffer; import org.apache.commons.collections.BufferUnderflowException; import org.apache.commons.collections.BulkTest; import org.apache.commons.collections.collection.AbstractTestCollection; /** * Test cases for CircularFifoBuffer. * * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ public class TestCircularFifoBuffer extends AbstractTestCollection { public TestCircularFifoBuffer(String n) { super(n); } public static Test suite() { return BulkTest.makeSuite(TestCircularFifoBuffer.class); } public static void main(String args[]) { TestRunner.run(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 void testRemoveError1() throws Exception { // based on bug 33071 CircularFifoBuffer fifo = new CircularFifoBuffer(5); fifo.add("1"); fifo.add("2"); fifo.add("3"); fifo.add("4"); fifo.add("5"); assertEquals("[1, 2, 3, 4, 5]", fifo.toString()); fifo.remove("3"); assertEquals("[1, 2, 4, 5]", fifo.toString()); fifo.remove("4"); assertEquals("[1, 2, 5]", fifo.toString()); } public void testRemoveError2() throws Exception { // based on bug 33071 CircularFifoBuffer fifo = new CircularFifoBuffer(5); fifo.add("1"); fifo.add("2"); fifo.add("3"); fifo.add("4"); fifo.add("5"); fifo.add("6"); assertEquals(5, fifo.size()); assertEquals("[2, 3, 4, 5, 6]", fifo.toString()); fifo.remove("3"); assertEquals("[2, 4, 5, 6]", fifo.toString()); fifo.remove("4"); assertEquals("[2, 5, 6]", fifo.toString()); } public void testRemoveError3() throws Exception { // based on bug 33071 CircularFifoBuffer fifo = new CircularFifoBuffer(5); fifo.add("1"); fifo.add("2"); fifo.add("3"); fifo.add("4"); fifo.add("5"); assertEquals("[1, 2, 3, 4, 5]", fifo.toString()); fifo.remove("3"); assertEquals("[1, 2, 4, 5]", fifo.toString()); fifo.add("6"); fifo.add("7"); assertEquals("[2, 4, 5, 6, 7]", fifo.toString()); fifo.remove("4"); assertEquals("[2, 5, 6, 7]", fifo.toString()); } public void testRemoveError4() throws Exception { // based on bug 33071 CircularFifoBuffer fifo = new CircularFifoBuffer(5); fifo.add("1"); fifo.add("2"); fifo.add("3"); fifo.add("4"); fifo.add("5"); // end=0 fifo.add("6"); // end=1 fifo.add("7"); // end=2 assertEquals("[3, 4, 5, 6, 7]", fifo.toString()); fifo.remove("4"); // remove element in middle of array, after start assertEquals("[3, 5, 6, 7]", fifo.toString()); } public void testRemoveError5() throws Exception { // based on bug 33071 CircularFifoBuffer fifo = new CircularFifoBuffer(5); fifo.add("1"); fifo.add("2"); fifo.add("3"); fifo.add("4"); fifo.add("5"); // end=0 fifo.add("6"); // end=1 fifo.add("7"); // end=2 assertEquals("[3, 4, 5, 6, 7]", fifo.toString()); fifo.remove("5"); // remove element at last pos in array assertEquals("[3, 4, 6, 7]", fifo.toString()); } public void testRemoveError6() throws Exception { // based on bug 33071 CircularFifoBuffer fifo = new CircularFifoBuffer(5); fifo.add("1"); fifo.add("2"); fifo.add("3"); fifo.add("4"); fifo.add("5"); // end=0 fifo.add("6"); // end=1 fifo.add("7"); // end=2 assertEquals("[3, 4, 5, 6, 7]", fifo.toString()); fifo.remove("6"); // remove element at position zero in array assertEquals("[3, 4, 5, 7]", fifo.toString()); } public void testRemoveError7() throws Exception { // based on bug 33071 CircularFifoBuffer fifo = new CircularFifoBuffer(5); fifo.add("1"); fifo.add("2"); fifo.add("3"); fifo.add("4"); fifo.add("5"); // end=0 fifo.add("6"); // end=1 fifo.add("7"); // end=2 assertEquals("[3, 4, 5, 6, 7]", fifo.toString()); fifo.remove("7"); // remove element at position one in array assertEquals("[3, 4, 5, 6]", fifo.toString()); } public void testRemoveError8() throws Exception { // based on bug 33071 CircularFifoBuffer fifo = new CircularFifoBuffer(5); fifo.add("1"); fifo.add("2"); fifo.add("3"); fifo.add("4"); fifo.add("5"); // end=0 fifo.add("6"); // end=1 fifo.add("7"); // end=2 fifo.add("8"); // end=3 assertEquals("[4, 5, 6, 7, 8]", fifo.toString()); fifo.remove("7"); // remove element at position one in array, need to shift 8 assertEquals("[4, 5, 6, 8]", fifo.toString()); } public void testRemoveError9() throws Exception { // based on bug 33071 CircularFifoBuffer fifo = new CircularFifoBuffer(5); fifo.add("1"); fifo.add("2"); fifo.add("3"); fifo.add("4"); fifo.add("5"); // end=0 fifo.add("6"); // end=1 fifo.add("7"); // end=2 fifo.add("8"); // end=3 assertEquals("[4, 5, 6, 7, 8]", fifo.toString()); fifo.remove("8"); // remove element at position two in array assertEquals("[4, 5, 6, 7]", fifo.toString()); } //----------------------------------------------------------------------- public void testRepeatedSerialization() throws Exception { // bug 31433 CircularFifoBuffer b = new CircularFifoBuffer(2); b.add("a"); assertEquals(1, b.size()); assertEquals(true, b.contains("a")); ByteArrayOutputStream bos = new ByteArrayOutputStream(); new ObjectOutputStream(bos).writeObject(b); CircularFifoBuffer b2 = (CircularFifoBuffer) new ObjectInputStream( new ByteArrayInputStream(bos.toByteArray())).readObject(); assertEquals(1, b2.size()); assertEquals(true, b2.contains("a")); b2.add("b"); assertEquals(2, b2.size()); assertEquals(true, b2.contains("a")); assertEquals(true, b2.contains("b")); bos = new ByteArrayOutputStream(); new ObjectOutputStream(bos).writeObject(b2); CircularFifoBuffer b3 = (CircularFifoBuffer) new ObjectInputStream( new ByteArrayInputStream(bos.toByteArray())).readObject(); assertEquals(2, b3.size()); assertEquals(true, b3.contains("a")); assertEquals(true, b3.contains("b")); b3.add("c"); assertEquals(2, b3.size()); assertEquals(true, b3.contains("b")); assertEquals(true, b3.contains("c")); } public String getCompatibilityVersion() { return "3.1"; } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk((java.io.Serializable) collection, "D:/dev/collections/data/test/CircularFifoBuffer.emptyCollection.version3.1.obj"); // resetFull(); // writeExternalFormToDisk((java.io.Serializable) collection, "D:/dev/collections/data/test/CircularFifoBuffer.fullCollection.version3.1.obj"); // } } ././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/buffer/TestPredicatedBuffer.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/buffer/TestPredicatedBuffe0000644000175000017500000001004310777673322032434 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.buffer; import java.util.Collection; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.collections.ArrayStack; import org.apache.commons.collections.Buffer; import org.apache.commons.collections.BufferUnderflowException; import org.apache.commons.collections.Predicate; import org.apache.commons.collections.collection.TestPredicatedCollection; /** * Extension of {@link TestPredicatedCollection} for exercising the * {@link PredicatedBuffer} implementation. * * @since Commons Collections 3.0 * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Phil Steitz */ 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/collections/data/test/PredicatedBuffer.emptyCollection.version3.1.obj"); // resetFull(); // writeExternalFormToDisk((java.io.Serializable) collection, "D:/dev/collections/data/test/PredicatedBuffer.fullCollection.version3.1.obj"); // } } ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/buffer/TestPriorityBuffer.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/buffer/TestPriorityBuffer.0000644000175000017500000003363110777673322032461 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.buffer; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Comparator; import java.util.Iterator; import java.util.Random; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.collections.Buffer; import org.apache.commons.collections.BufferUnderflowException; import org.apache.commons.collections.ComparatorUtils; import org.apache.commons.collections.collection.AbstractTestCollection; import org.apache.commons.collections.comparators.ComparableComparator; import org.apache.commons.collections.comparators.ReverseComparator; /** * Tests the PriorityBuffer. * * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Michael A. Smith * @author Steve Phelps */ 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; 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(); } /** * Generates 500 randomly initialized heaps of size 100 * and tests that after serializing and restoring them to a byte array * that the following conditions hold: * * - the size of the restored heap is the same * as the size of the orignal heap * * - all elements in the original heap are present in the restored heap * * - the heap order of the restored heap is intact as * verified by checkOrder() */ public void testSerialization() { int iterations = 500; int heapSize = 100; PriorityBuffer h; Random randGenerator = new Random(); 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))); } assertTrue(h.size() == heapSize); PriorityBuffer h1 = serializeAndRestore(h); assertTrue(h1.size() == heapSize); Iterator hit = h.iterator(); while (hit.hasNext()) { Integer n = (Integer) hit.next(); assertTrue(h1.contains(n)); } checkOrder(h1); } } public PriorityBuffer serializeAndRestore(PriorityBuffer h) { PriorityBuffer h1 = null; try { byte[] objekt = writeExternalFormToBytes(h); h1 = (PriorityBuffer) readExternalFormFromBytes(objekt); } catch (IOException e) { e.printStackTrace(); fail(e.toString()); } catch (ClassNotFoundException e) { e.printStackTrace(); fail(e.toString()); } return h1; } public String getCompatibilityVersion() { return "3.2"; } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk((java.io.Serializable) collection, "C:/commons/collections/data/test/PriorityBuffer.emptyCollection.version3.2.obj"); // resetFull(); // writeExternalFormToDisk((java.io.Serializable) collection, "C:/commons/collections/data/test/PriorityBuffer.fullCollection.version3.2.obj"); // } } ././@LongLink0000000000000000000000000000015500000000000011566 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/buffer/TestSynchronizedBuffer.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/buffer/TestSynchronizedBuf0000644000175000017500000000630710777673322032544 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.buffer; import java.util.Arrays; import java.util.Collection; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.collections.ArrayStack; import org.apache.commons.collections.Buffer; import org.apache.commons.collections.collection.AbstractTestCollection; /** * Extension of {@link AbstractTestCollection} for exercising the * {@link SynchronizedBuffer} implementation. * * @since Commons Collections 3.1 * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Phil Steitz * @author Stephen Colebourne */ 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/collections/data/test/SynchronizedBuffer.emptyCollection.version3.1.obj"); // resetFull(); // writeExternalFormToDisk((java.io.Serializable) collection, "D:/dev/collections/data/test/SynchronizedBuffer.fullCollection.version3.1.obj"); // } } ././@LongLink0000000000000000000000000000015400000000000011565 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/buffer/TestTransformedBuffer.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/buffer/TestTransformedBuff0000644000175000017500000000503510777673322032514 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.buffer; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.apache.commons.collections.ArrayStack; import org.apache.commons.collections.Buffer; import org.apache.commons.collections.collection.TestTransformedCollection; /** * Extension of {@link TestBuffer} for exercising the {@link TransformedBuffer} * implementation. * * @since Commons Collections 3.0 * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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]))); } } ././@LongLink0000000000000000000000000000015600000000000011567 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/buffer/TestUnboundedFifoBuffer.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/buffer/TestUnboundedFifoBu0000644000175000017500000003307210777673322032445 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.buffer; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import junit.framework.Test; import org.apache.commons.collections.BulkTest; import org.apache.commons.collections.collection.AbstractTestCollection; /** * Test cases for UnboundedFifoBuffer. * * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Unknown */ 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 void testInternalStateAdd() { UnboundedFifoBuffer test = new UnboundedFifoBuffer(2); assertEquals(3, test.buffer.length); assertEquals(0, test.head); assertEquals(0, test.tail); test.add("A"); assertEquals(3, test.buffer.length); assertEquals(0, test.head); assertEquals(1, test.tail); test.add("B"); assertEquals(3, test.buffer.length); assertEquals(0, test.head); assertEquals(2, test.tail); test.add("C"); // forces buffer increase assertEquals(5, test.buffer.length); assertEquals(0, test.head); assertEquals(3, test.tail); test.add("D"); assertEquals(5, test.buffer.length); assertEquals(0, test.head); assertEquals(4, test.tail); } public void testInternalStateAddWithWrap() { UnboundedFifoBuffer test = new UnboundedFifoBuffer(3); assertEquals(4, test.buffer.length); assertEquals(0, test.head); assertEquals(0, test.tail); test.add("A"); assertEquals(4, test.buffer.length); assertEquals(0, test.head); assertEquals(1, test.tail); test.add("B"); assertEquals(4, test.buffer.length); assertEquals(0, test.head); assertEquals(2, test.tail); test.add("C"); assertEquals(4, test.buffer.length); assertEquals(0, test.head); assertEquals(3, test.tail); test.remove("A"); assertEquals(4, test.buffer.length); assertEquals(1, test.head); assertEquals(3, test.tail); test.remove("B"); assertEquals(4, test.buffer.length); assertEquals(2, test.head); assertEquals(3, test.tail); test.add("D"); assertEquals(4, test.buffer.length); assertEquals(2, test.head); assertEquals(0, test.tail); test.add("E"); assertEquals(4, test.buffer.length); assertEquals(2, test.head); assertEquals(1, test.tail); } public void testInternalStateRemove1() { UnboundedFifoBuffer test = new UnboundedFifoBuffer(4); test.add("A"); test.add("B"); test.add("C"); assertEquals(5, test.buffer.length); assertEquals(0, test.head); assertEquals(3, test.tail); test.remove("A"); assertEquals(5, test.buffer.length); assertEquals(1, test.head); assertEquals(3, test.tail); test.add("D"); assertEquals(5, test.buffer.length); assertEquals(1, test.head); assertEquals(4, test.tail); } public void testInternalStateRemove2() { UnboundedFifoBuffer test = new UnboundedFifoBuffer(4); test.add("A"); test.add("B"); test.add("C"); assertEquals(5, test.buffer.length); assertEquals(0, test.head); assertEquals(3, test.tail); test.remove("B"); assertEquals(5, test.buffer.length); assertEquals(0, test.head); assertEquals(2, test.tail); test.add("D"); assertEquals(5, test.buffer.length); assertEquals(0, test.head); assertEquals(3, test.tail); } public void testInternalStateIteratorRemove1() { UnboundedFifoBuffer test = new UnboundedFifoBuffer(4); test.add("A"); test.add("B"); test.add("C"); assertEquals(5, test.buffer.length); assertEquals(0, test.head); assertEquals(3, test.tail); Iterator it = test.iterator(); it.next(); it.remove(); assertEquals(5, test.buffer.length); assertEquals(1, test.head); assertEquals(3, test.tail); test.add("D"); assertEquals(5, test.buffer.length); assertEquals(1, test.head); assertEquals(4, test.tail); } public void testInternalStateIteratorRemove2() { UnboundedFifoBuffer test = new UnboundedFifoBuffer(4); test.add("A"); test.add("B"); test.add("C"); Iterator it = test.iterator(); it.next(); it.next(); it.remove(); assertEquals(5, test.buffer.length); assertEquals(0, test.head); assertEquals(2, test.tail); test.add("D"); assertEquals(5, test.buffer.length); assertEquals(0, test.head); assertEquals(3, test.tail); } public void testInternalStateIteratorRemoveWithTailAtEnd1() { UnboundedFifoBuffer test = new UnboundedFifoBuffer(3); test.add("A"); test.add("B"); test.add("C"); test.remove("A"); test.add("D"); assertEquals(4, test.buffer.length); assertEquals(1, test.head); assertEquals(0, test.tail); Iterator it = test.iterator(); assertEquals("B", it.next()); it.remove(); assertEquals(4, test.buffer.length); assertEquals(2, test.head); assertEquals(0, test.tail); } public void testInternalStateIteratorRemoveWithTailAtEnd2() { UnboundedFifoBuffer test = new UnboundedFifoBuffer(3); test.add("A"); test.add("B"); test.add("C"); test.remove("A"); test.add("D"); assertEquals(4, test.buffer.length); assertEquals(1, test.head); assertEquals(0, test.tail); Iterator it = test.iterator(); assertEquals("B", it.next()); assertEquals("C", it.next()); it.remove(); assertEquals(4, test.buffer.length); assertEquals(1, test.head); assertEquals(3, test.tail); } public void testInternalStateIteratorRemoveWithTailAtEnd3() { UnboundedFifoBuffer test = new UnboundedFifoBuffer(3); test.add("A"); test.add("B"); test.add("C"); test.remove("A"); test.add("D"); assertEquals(4, test.buffer.length); assertEquals(1, test.head); assertEquals(0, test.tail); Iterator it = test.iterator(); assertEquals("B", it.next()); assertEquals("C", it.next()); assertEquals("D", it.next()); it.remove(); assertEquals(4, test.buffer.length); assertEquals(1, test.head); assertEquals(3, test.tail); } public void testInternalStateIteratorRemoveWithWrap1() { UnboundedFifoBuffer test = new UnboundedFifoBuffer(3); test.add("A"); test.add("B"); test.add("C"); test.remove("A"); test.remove("B"); test.add("D"); test.add("E"); assertEquals(4, test.buffer.length); assertEquals(2, test.head); assertEquals(1, test.tail); Iterator it = test.iterator(); assertEquals("C", it.next()); it.remove(); assertEquals(4, test.buffer.length); assertEquals(3, test.head); assertEquals(1, test.tail); } public void testInternalStateIteratorRemoveWithWrap2() { UnboundedFifoBuffer test = new UnboundedFifoBuffer(3); test.add("A"); test.add("B"); test.add("C"); test.remove("A"); test.remove("B"); test.add("D"); test.add("E"); assertEquals(4, test.buffer.length); assertEquals(2, test.head); assertEquals(1, test.tail); Iterator it = test.iterator(); assertEquals("C", it.next()); assertEquals("D", it.next()); it.remove(); assertEquals(4, test.buffer.length); assertEquals(2, test.head); assertEquals(0, test.tail); } public void testInternalStateIteratorRemoveWithWrap3() { UnboundedFifoBuffer test = new UnboundedFifoBuffer(3); test.add("A"); test.add("B"); test.add("C"); test.remove("A"); test.remove("B"); test.add("D"); test.add("E"); assertEquals(4, test.buffer.length); assertEquals(2, test.head); assertEquals(1, test.tail); Iterator it = test.iterator(); assertEquals("C", it.next()); assertEquals("D", it.next()); assertEquals("E", it.next()); it.remove(); assertEquals(4, test.buffer.length); assertEquals(2, test.head); assertEquals(0, test.tail); } //----------------------------------------------------------------------- public String getCompatibilityVersion() { return "3.1"; } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk((java.io.Serializable) collection, "D:/dev/collections/data/test/UnboundedFifoBuffer.emptyCollection.version3.1.obj"); // resetFull(); // writeExternalFormToDisk((java.io.Serializable) collection, "D:/dev/collections/data/test/UnboundedFifoBuffer.fullCollection.version3.1.obj"); // } } ././@LongLink0000000000000000000000000000015500000000000011566 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/buffer/TestUnmodifiableBuffer.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/buffer/TestUnmodifiableBuf0000644000175000017500000000711510777673322032461 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.buffer; import java.util.Arrays; import java.util.Collection; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.collections.ArrayStack; import org.apache.commons.collections.Buffer; import org.apache.commons.collections.collection.AbstractTestCollection; /** * Extension of {@link AbstractTestCollection} for exercising the * {@link UnmodifiableBuffer} implementation. * * @since Commons Collections 3.1 * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Phil Steitz * @author Stephen Colebourne */ 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/collections/data/test/UnmodifiableBuffer.emptyCollection.version3.1.obj"); // resetFull(); // writeExternalFormToDisk((java.io.Serializable) collection, "D:/dev/collections/data/test/UnmodifiableBuffer.fullCollection.version3.1.obj"); // } } libcommons-collections3-java.orig/src/test/org/apache/commons/collections/collection/0000755000175000017500000000000011010124151027465 5ustar godgod././@LongLink0000000000000000000000000000016100000000000011563 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/collection/AbstractTestCollection.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/collection/AbstractTestCol0000644000175000017500000014215710777673312032516 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.collection; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.ConcurrentModificationException; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import org.apache.commons.collections.AbstractTestObject; /** * 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 collections 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 collections, * 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 collections.

              *

              * 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. * * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Rodney Waldhoff * @author Paul Jack * @author Michael A. Smith * @author Neil O'Toole * @author Stephen Colebourne */ 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 collections 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 collections 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 collections 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 * collections. 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 * collections. 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(); } /** * 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; resetEmpty(); try { collection.add(new Object()); 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(new Object()); 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); } } } } libcommons-collections3-java.orig/src/test/org/apache/commons/collections/collection/TestAll.java0000644000175000017500000000357310777673312031743 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.collection; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * Entry point for tests. * * @since Commons Collections 3.0 * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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; } } ././@LongLink0000000000000000000000000000016200000000000011564 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/collection/TestCompositeCollection.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/collection/TestCompositeCo0000644000175000017500000002571010777673312032534 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.collection; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import junit.framework.Test; import junit.framework.TestSuite; /** * Extension of {@link AbstractTestCollection} for exercising the * {@link CompositeCollection} implementation. * * @since Commons Collections 3.0 * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Brian McCallister * @author Phil Steitz */ 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 collections, 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); } } ././@LongLink0000000000000000000000000000016300000000000011565 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/collection/TestPredicatedCollection.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/collection/TestPredicatedC0000644000175000017500000001205510777673312032455 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.collection; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.collections.Predicate; import org.apache.commons.collections.PredicateUtils; /** * Extension of {@link TestCollection} for exercising the * {@link PredicatedCollection} implementation. * * @since Commons Collections 3.0 * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Phil Steitz */ 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/collections/data/test/PredicatedCollection.emptyCollection.version3.1.obj"); // resetFull(); // writeExternalFormToDisk((java.io.Serializable) collection, "D:/dev/collections/data/test/PredicatedCollection.fullCollection.version3.1.obj"); // } } ././@LongLink0000000000000000000000000000016500000000000011567 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/collection/TestSynchronizedCollection.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/collection/TestSynchronize0000644000175000017500000000544210777673312032623 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.collection; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import junit.framework.Test; import junit.framework.TestSuite; /** * Extension of {@link AbstractTestCollection} for exercising the * {@link SynchronizedCollection} implementation. * * @since Commons Collections 3.1 * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Phil Steitz * @author Stephen Colebourne */ 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/collections/data/test/SynchronizedCollection.emptyCollection.version3.1.obj"); // resetFull(); // writeExternalFormToDisk((java.io.Serializable) collection, "D:/dev/collections/data/test/SynchronizedCollection.fullCollection.version3.1.obj"); // } } ././@LongLink0000000000000000000000000000016400000000000011566 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/collection/TestTransformedCollection.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/collection/TestTransformed0000644000175000017500000001063510777673312032574 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.collection; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.collections.Transformer; import org.apache.commons.collections.TransformerUtils; /** * Extension of {@link TestCollection} for exercising the {@link TransformedCollection} * implementation. * * @since Commons Collections 3.0 * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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/collections/data/test/TransformedCollection.emptyCollection.version3.1.obj"); // resetFull(); // writeExternalFormToDisk((java.io.Serializable) collection, "D:/dev/collections/data/test/TransformedCollection.fullCollection.version3.1.obj"); // } } ././@LongLink0000000000000000000000000000016500000000000011567 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/collection/TestUnmodifiableCollection.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/collection/TestUnmodifiabl0000644000175000017500000000623710777673312032544 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.collection; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import junit.framework.Test; import junit.framework.TestSuite; /** * Extension of {@link AbstractTestCollection} for exercising the * {@link UnmodifiableCollection} implementation. * * @since Commons Collections 3.0 * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Phil Steitz * @author Stephen Colebourne */ 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/collections/data/test/UnmodifiableCollection.emptyCollection.version3.1.obj"); // resetFull(); // writeExternalFormToDisk((java.io.Serializable) collection, "D:/dev/collections/data/test/UnmodifiableCollection.fullCollection.version3.1.obj"); // } } libcommons-collections3-java.orig/src/test/org/apache/commons/collections/comparators/0000755000175000017500000000000011010124151027664 5ustar godgod././@LongLink0000000000000000000000000000016200000000000011564 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/comparators/AbstractTestComparator.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/comparators/AbstractTestCo0000644000175000017500000001655110777673310032535 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.comparators; 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; import org.apache.commons.collections.AbstractTestObject; /** * 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 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()) { 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)); } } } libcommons-collections3-java.orig/src/test/org/apache/commons/collections/comparators/TestAll.java0000644000175000017500000000360510777673310032134 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.comparators; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * Entry point for all Comparator Collections tests. * * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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); } } ././@LongLink0000000000000000000000000000016100000000000011563 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/comparators/TestBooleanComparator.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/comparators/TestBooleanCom0000644000175000017500000002052410777673310032521 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.comparators; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import junit.framework.Test; import junit.framework.TestSuite; /** * Tests for {@link BooleanComparator}. * * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Rodney Waldhoff */ public class TestBooleanComparator extends AbstractTestComparator { // conventional // ------------------------------------------------------------------------ public TestBooleanComparator(String testName) { super(testName); } public static Test suite() { return new TestSuite(TestBooleanComparator.class); } // collections 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((Object)(Boolean.TRUE),(Object)(Boolean.TRUE))); assertEquals(0,comp.compare((Object)(Boolean.FALSE),(Object)(Boolean.FALSE))); assertTrue(comp.compare((Object)(Boolean.FALSE),(Object)(Boolean.TRUE)) > 0); assertTrue(comp.compare((Object)(Boolean.TRUE),(Object)(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((Object)(Boolean.TRUE),(Object)(Boolean.TRUE))); assertEquals(0,comp.compare((Object)(Boolean.FALSE),(Object)(Boolean.FALSE))); assertTrue(comp.compare((Object)(Boolean.FALSE),(Object)(Boolean.TRUE)) < 0); assertTrue(comp.compare((Object)(Boolean.TRUE),(Object)(Boolean.FALSE)) > 0); } protected void orderIndependentTests(BooleanComparator comp) { nullArgumentTests(comp); nonBooleanArgumentTests(comp); nullAndNonBooleanArgumentsTests(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); try { comp.compare("string","string"); fail("Expected ClassCastException"); } catch(ClassCastException e) { // expected } try { comp.compare(Boolean.TRUE,"string"); fail("Expected ClassCastException"); } catch(ClassCastException e) { // expected } try { comp.compare("string",Boolean.TRUE); fail("Expected ClassCastException"); } catch(ClassCastException e) { // expected } try { comp.compare("string",new Integer(3)); fail("Expected ClassCastException"); } catch(ClassCastException e) { // expected } try { comp.compare(new Integer(3),"string"); fail("Expected ClassCastException"); } catch(ClassCastException e) { // expected } } protected void nullAndNonBooleanArgumentsTests(BooleanComparator comp) { assertNotNull(comp); try { comp.compare(null,"string"); fail("Expected ClassCast or NullPointer Exception"); } catch(ClassCastException e) { // expected } catch(NullPointerException e) { // expected } try { comp.compare("string",null); fail("Expected ClassCast or NullPointer Exception"); } catch(ClassCastException e) { // expected } catch(NullPointerException e) { // expected } } } ././@LongLink0000000000000000000000000000016400000000000011566 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/comparators/TestComparableComparator.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/comparators/TestComparable0000644000175000017500000000351010777673310032544 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.comparators; import java.util.Comparator; import java.util.LinkedList; import java.util.List; import junit.framework.Test; import junit.framework.TestSuite; /** * Tests for ComparableComparator. * * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Unknown */ 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; } } ././@LongLink0000000000000000000000000000015700000000000011570 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/comparators/TestComparatorChain.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/comparators/TestComparator0000644000175000017500000001611010777673310032606 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.comparators; import java.io.Serializable; import java.util.Comparator; import java.util.LinkedList; import java.util.List; import junit.framework.Test; import junit.framework.TestSuite; /** * Tests for ComparatorChain. * * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Unknown */ 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; } } ././@LongLink0000000000000000000000000000016400000000000011566 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/comparators/TestFixedOrderComparator.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/comparators/TestFixedOrder0000644000175000017500000002047110777673310032537 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.comparators; import java.util.Arrays; import java.util.Comparator; import java.util.LinkedList; import java.util.List; import java.util.Random; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * Test class for FixedOrderComparator. * * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author David Leppik * @author Stephen Colebourne */ 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]); } } } ././@LongLink0000000000000000000000000000015600000000000011567 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/comparators/TestNullComparator.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/comparators/TestNullCompar0000644000175000017500000000640210777673310032556 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.comparators; import java.util.Comparator; import java.util.LinkedList; import java.util.List; import junit.framework.Test; import junit.framework.TestSuite; /** * Test the NullComparator. * * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Michael A. Smith */ 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(); } 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(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"; } } } ././@LongLink0000000000000000000000000000016100000000000011563 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/comparators/TestReverseComparator.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/comparators/TestReverseCom0000644000175000017500000000634110777673310032556 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.comparators; 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; import junit.framework.Test; import junit.framework.TestSuite; /** * Tests for ReverseComparator. * * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Unknown */ 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); } } libcommons-collections3-java.orig/src/test/org/apache/commons/collections/functors/0000755000175000017500000000000010777673433027234 5ustar godgodlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/iterators/0000755000175000017500000000000011010124151027346 5ustar godgod././@LongLink0000000000000000000000000000015600000000000011567 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/iterators/AbstractTestIterator.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/iterators/AbstractTestIter0000644000175000017500000001373410777673354032571 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.iterators; import java.util.Iterator; import java.util.NoSuchElementException; import org.apache.commons.collections.AbstractTestObject; /** * 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. * * @since Commons Collections 3.0 * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Morgan Delagrange * @author Stephen Colebourne */ 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) {} } } ././@LongLink0000000000000000000000000000016200000000000011564 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/iterators/AbstractTestListIterator.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/iterators/AbstractTestList0000644000175000017500000002153610777673354032600 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.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. * * @since Commons Collections 3.0 * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Rodney Waldhoff * @author Stephen Colebourne */ 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) { } } } } ././@LongLink0000000000000000000000000000016100000000000011563 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/iterators/AbstractTestMapIterator.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/iterators/AbstractTestMapI0000644000175000017500000002663610777673354032521 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.iterators; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; import org.apache.commons.collections.MapIterator; /** * 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. * * @since Commons Collections 3.0 * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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(); } } ././@LongLink0000000000000000000000000000017000000000000011563 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/iterators/AbstractTestOrderedMapIterator.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/iterators/AbstractTestOrde0000644000175000017500000001362710777673354032560 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.iterators; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; import org.apache.commons.collections.OrderedMapIterator; /** * 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. * * @since Commons Collections 3.0 * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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()); } } libcommons-collections3-java.orig/src/test/org/apache/commons/collections/iterators/TestAll.java0000644000175000017500000000556710777673354031637 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.iterators; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * Entry point for all iterator tests. * * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Rodney Waldhoff */ 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(TestLoopingListIterator.suite()); suite.addTest(TestReverseListIterator.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); } } ././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/iterators/TestArrayIterator.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/iterators/TestArrayIterato0000644000175000017500000000660110777673354032603 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.iterators; import java.util.Iterator; import java.util.NoSuchElementException; import junit.framework.Test; import junit.framework.TestSuite; /** * 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. * * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author James Strachan * @author Mauricio S. Moura * @author Morgan Delagrange * @author Stephen Colebourne */ 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()); } } ././@LongLink0000000000000000000000000000015400000000000011565 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/iterators/TestArrayIterator2.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/iterators/TestArrayIterato0000644000175000017500000001466210777673354032611 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.iterators; import java.util.Iterator; import java.util.NoSuchElementException; import junit.framework.Test; import junit.framework.TestSuite; /** * Tests the ArrayIterator with primitive type arrays. * * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Morgan Delagrange * @author James Strachan */ 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 } } } ././@LongLink0000000000000000000000000000015700000000000011570 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/iterators/TestArrayListIterator.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/iterators/TestArrayListIte0000644000175000017500000000776510777673354032565 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.iterators; import java.util.Arrays; import java.util.Iterator; import java.util.ListIterator; import java.util.NoSuchElementException; import junit.framework.Test; import junit.framework.TestSuite; /** * Test the ArrayListIterator class. * * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * @author Neil O'Toole */ 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()); } } } ././@LongLink0000000000000000000000000000016000000000000011562 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/iterators/TestArrayListIterator2.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/iterators/TestArrayListIte0000644000175000017500000000412610777673354032551 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.iterators; import java.util.Iterator; import junit.framework.Test; import junit.framework.TestSuite; /** * Test the ArrayListIterator class with primitives. * * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * @author Neil O'Toole */ 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); } } ././@LongLink0000000000000000000000000000015700000000000011570 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/iterators/TestCollatingIterator.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/iterators/TestCollatingIte0000644000175000017500000001765710777673354032570 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.iterators; import java.util.ArrayList; import java.util.Comparator; import java.util.Iterator; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.collections.comparators.ComparableComparator; /** * Unit test suite for {@link CollatingIterator}. * * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * @author Rodney Waldhoff */ 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 -1; --i) { Object testValue = testArray[i]; Object iterValue = iter.previous(); assertEquals( "Iteration value is correct", testValue, iterValue ); } try { 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) { } } public void testReset() { ResettableListIterator iter = (ResettableListIterator) makeFullIterator(); Object first = iter.next(); Object second = iter.next(); iter.reset(); // after reset, there shouldn't be any previous elements assertFalse("No previous elements after reset()", iter.hasPrevious()); // after reset, the results should be the same as before assertEquals("First element should be the same", first, iter.next()); assertEquals("Second elment should be the same", second, iter.next()); // after passing the point, where we resetted, continuation should work as expected for (int i = 2; i < testArray.length; i++) { Object testValue = testArray[i]; Object iterValue = iter.next(); assertEquals("Iteration value is correct", testValue, iterValue); } } } ././@LongLink0000000000000000000000000000015500000000000011566 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/iterators/TestLoopingIterator.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/iterators/TestLoopingItera0000644000175000017500000001621010777673354032566 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.iterators; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.NoSuchElementException; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * Tests the LoopingIterator class. * * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Jonathan Carlson * @author Stephen Colebourne */ 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()); } } ././@LongLink0000000000000000000000000000016100000000000011563 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/iterators/TestLoopingListIterator.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/iterators/TestLoopingListI0000644000175000017500000003255010777673354032553 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.iterators; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.NoSuchElementException; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * Tests the LoopingListIterator class. * * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Eric Crampton */ public class TestLoopingListIterator extends TestCase { public TestLoopingListIterator(String testName) { super(testName); } public static Test suite() { return new TestSuite(TestLoopingListIterator.class); } /** * Tests constructor exception. */ public void testConstructorEx() throws Exception { try { new LoopingListIterator(null); fail(); } catch (NullPointerException ex) { } } /** * Tests whether an empty looping list iterator works. */ public void testLooping0() throws Exception { List list = new ArrayList(); LoopingListIterator loop = new LoopingListIterator(list); assertFalse(loop.hasNext()); assertFalse(loop.hasPrevious()); try { loop.next(); fail(); } catch (NoSuchElementException ex) { } try { loop.previous(); fail(); } catch (NoSuchElementException ex) { } } /** * Tests whether a looping list iterator works on a list with only * one element. */ public void testLooping1() throws Exception { List list = new ArrayList(Arrays.asList(new String[] { "a" })); LoopingListIterator loop = new LoopingListIterator(list); // assertTrue(loop.hasNext()); assertEquals("a", loop.next()); // assertTrue(loop.hasNext()); assertEquals("a", loop.next()); // assertTrue(loop.hasNext()); assertEquals("a", loop.next()); // assertTrue(loop.hasPrevious()); assertEquals("a", loop.previous()); // assertTrue(loop.hasPrevious()); assertEquals("a", loop.previous()); // assertTrue(loop.hasPrevious()); assertEquals("a", loop.previous()); // } /** * Tests whether a looping list iterator works on a list with two * elements. */ public void testLooping2() throws Exception { List list = new ArrayList(Arrays.asList(new String[] { "a", "b" })); LoopingListIterator loop = new LoopingListIterator(list); // b assertTrue(loop.hasNext()); assertEquals("a", loop.next()); // a assertTrue(loop.hasNext()); assertEquals("b", loop.next()); // b assertTrue(loop.hasNext()); assertEquals("a", loop.next()); // a // Reset the iterator and try using previous. loop.reset(); // b assertTrue(loop.hasPrevious()); assertEquals("b", loop.previous()); // a assertTrue(loop.hasPrevious()); assertEquals("a", loop.previous()); // b assertTrue(loop.hasPrevious()); assertEquals("b", loop.previous()); // a } /** * Tests jogging back and forth between two elements, but not over * the begin/end boundary of the list. */ public void testJoggingNotOverBoundary() { List list = new ArrayList(Arrays.asList(new String[] { "a", "b" })); LoopingListIterator loop = new LoopingListIterator(list); // b // Try jogging back and forth between the elements, but not // over the begin/end boundary. loop.reset(); assertEquals("a", loop.next()); // a assertEquals("a", loop.previous()); // b assertEquals("a", loop.next()); // a assertEquals("b", loop.next()); // b assertEquals("b", loop.previous()); // a assertEquals("b", loop.next()); // b } /** * Tests jogging back and forth between two elements over the * begin/end boundary of the list. */ public void testJoggingOverBoundary() { List list = new ArrayList(Arrays.asList(new String[] { "a", "b" })); LoopingListIterator loop = new LoopingListIterator(list); // b // Try jogging back and forth between the elements, but not // over the begin/end boundary. assertEquals("b", loop.previous()); // a assertEquals("b", loop.next()); // b assertEquals("b", loop.previous()); // a assertEquals("a", loop.previous()); // b assertEquals("a", loop.next()); // a assertEquals("a", loop.previous()); // b } /** * Tests removing an element from a wrapped ArrayList. */ public void testRemovingElementsAndIteratingForward() { List list = new ArrayList(Arrays.asList(new String[] { "a", "b", "c" })); LoopingListIterator loop = new LoopingListIterator(list); // b c assertTrue(loop.hasNext()); assertEquals("a", loop.next()); // a c loop.remove(); // c assertEquals(2, list.size()); assertTrue(loop.hasNext()); assertEquals("b", loop.next()); // b loop.remove(); // assertEquals(1, list.size()); assertTrue(loop.hasNext()); assertEquals("c", loop.next()); // loop.remove(); // --- assertEquals(0, list.size()); assertFalse(loop.hasNext()); try { loop.next(); fail(); } catch (NoSuchElementException ex) { } } /** * Tests removing an element from a wrapped ArrayList. */ public void testRemovingElementsAndIteratingBackwards() { List list = new ArrayList(Arrays.asList(new String[] { "a", "b", "c" })); LoopingListIterator loop = new LoopingListIterator(list); // b c assertTrue(loop.hasPrevious()); assertEquals("c", loop.previous()); // a b loop.remove(); // b assertEquals(2, list.size()); assertTrue(loop.hasPrevious()); assertEquals("b", loop.previous()); // a loop.remove(); // assertEquals(1, list.size()); assertTrue(loop.hasPrevious()); assertEquals("a", loop.previous()); // loop.remove(); // --- assertEquals(0, list.size()); assertFalse(loop.hasPrevious()); try { loop.previous(); fail(); } catch (NoSuchElementException ex) { } } /** * Tests the reset method. */ public void testReset() { List list = new ArrayList(Arrays.asList(new String[] { "a", "b", "c" })); LoopingListIterator loop = new LoopingListIterator(list); // b c assertEquals("a", loop.next()); // a c assertEquals("b", loop.next()); // a b loop.reset(); // b c assertEquals("a", loop.next()); // a c loop.reset(); // b c assertEquals("a", loop.next()); // a c assertEquals("b", loop.next()); // a b assertEquals("c", loop.next()); // b c loop.reset(); // b c assertEquals("c", loop.previous()); // a b assertEquals("b", loop.previous()); // a c loop.reset(); // b c assertEquals("c", loop.previous()); // a b loop.reset(); // b c assertEquals("c", loop.previous()); // a b assertEquals("b", loop.previous()); // a c assertEquals("a", loop.previous()); // b c } /** * Tests the add method. */ public void testAdd() { List list = new ArrayList(Arrays.asList(new String[] { "b", "e", "f" })); LoopingListIterator loop = new LoopingListIterator(list); // e f loop.add("a"); // b e f assertEquals("b", loop.next()); // a e f loop.reset(); // b e f assertEquals("a", loop.next()); // a e f assertEquals("b", loop.next()); // a b f loop.add("c"); // a b c f assertEquals("e", loop.next()); // a b c e assertEquals("e", loop.previous()); // a b c f assertEquals("c", loop.previous()); // a b e f assertEquals("c", loop.next()); // a b c f loop.add("d"); // a b c d f loop.reset(); // b c d e f assertEquals("a", loop.next()); // a c d e f assertEquals("b", loop.next()); // a b d e f assertEquals("c", loop.next()); // a b c e f assertEquals("d", loop.next()); // a b c d f assertEquals("e", loop.next()); // a b c d e assertEquals("f", loop.next()); // b c d e f assertEquals("a", loop.next()); // a c d e f list = new ArrayList(Arrays.asList(new String[] { "b", "e", "f" })); loop = new LoopingListIterator(list); // e f loop.add("a"); // a e f assertEquals("a", loop.previous()); // a b e loop.reset(); // b e f assertEquals("f", loop.previous()); // a b e assertEquals("e", loop.previous()); // a b f loop.add("d"); // a b d f assertEquals("d", loop.previous()); // a b e f loop.add("c"); // a b c e f assertEquals("c", loop.previous()); // a b d e f loop.reset(); assertEquals("a", loop.next()); // a c d e f assertEquals("b", loop.next()); // a b d e f assertEquals("c", loop.next()); // a b c e f assertEquals("d", loop.next()); // a b c d f assertEquals("e", loop.next()); // a b c d e assertEquals("f", loop.next()); // b c d e f assertEquals("a", loop.next()); // a c d e f } /** * Tests nextIndex and previousIndex. */ public void testNextAndPreviousIndex() { List list = new ArrayList(Arrays.asList(new String[] { "a", "b", "c" })); LoopingListIterator loop = new LoopingListIterator(list); // b c assertEquals(0, loop.nextIndex()); assertEquals(2, loop.previousIndex()); assertEquals("a", loop.next()); // a c assertEquals(1, loop.nextIndex()); assertEquals(0, loop.previousIndex()); assertEquals("a", loop.previous()); // b c assertEquals(0, loop.nextIndex()); assertEquals(2, loop.previousIndex()); assertEquals("c", loop.previous()); // a b assertEquals(2, loop.nextIndex()); assertEquals(1, loop.previousIndex()); assertEquals("b", loop.previous()); // a c assertEquals(1, loop.nextIndex()); assertEquals(0, loop.previousIndex()); assertEquals("a", loop.previous()); // b c assertEquals(0, loop.nextIndex()); assertEquals(2, loop.previousIndex()); } /** * Tests using the set method to change elements. */ public void testSet() { List list = new ArrayList(Arrays.asList(new String[] { "q", "r", "z" })); LoopingListIterator loop = new LoopingListIterator(list); // r z assertEquals("z", loop.previous()); // q r loop.set("c"); // q r loop.reset(); // r c assertEquals("q", loop.next()); // q c loop.set("a"); // a c assertEquals("r", loop.next()); // a r loop.set("b"); // a b loop.reset(); // b c assertEquals("a", loop.next()); // a c assertEquals("b", loop.next()); // a b assertEquals("c", loop.next()); // b c } } ././@LongLink0000000000000000000000000000016100000000000011563 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/iterators/TestObjectArrayIterator.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/iterators/TestObjectArrayI0000644000175000017500000001003710777673354032511 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.iterators; import java.util.Iterator; import java.util.NoSuchElementException; import junit.framework.Test; import junit.framework.TestSuite; /** * Tests the ObjectArrayIterator. * * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author James Strachan * @author Mauricio S. Moura * @author Morgan Delagrange * @author Stephen Colebourne */ 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()); } } ././@LongLink0000000000000000000000000000016500000000000011567 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/iterators/TestObjectArrayListIterator.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/iterators/TestObjectArrayL0000644000175000017500000000774610777673354032531 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.iterators; import java.util.Arrays; import java.util.Iterator; import java.util.ListIterator; import java.util.NoSuchElementException; import junit.framework.Test; import junit.framework.TestSuite; /** * Tests the ObjectArrayListIterator class. * * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Neil O'Toole */ 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()); } } } ././@LongLink0000000000000000000000000000016600000000000011570 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/iterators/TestObjectArrayListIterator2.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/iterators/TestObjectArrayL0000644000175000017500000000375410777673354032524 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.iterators; import java.util.ListIterator; import junit.framework.Test; import junit.framework.TestSuite; /** * Tests the ObjectArrayListIterator class. * * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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; } } ././@LongLink0000000000000000000000000000016100000000000011563 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/iterators/TestObjectGraphIterator.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/iterators/TestObjectGraphI0000644000175000017500000003375010777673354032503 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.iterators; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import junit.framework.Test; import junit.framework.TestSuite; import junit.textui.TestRunner; import org.apache.commons.collections.IteratorUtils; import org.apache.commons.collections.Transformer; /** * Testcase. * * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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; } } } ././@LongLink0000000000000000000000000000016100000000000011563 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/iterators/TestReverseListIterator.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/iterators/TestReverseListI0000644000175000017500000001433510777673354032560 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.iterators; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.ListIterator; import java.util.NoSuchElementException; import junit.framework.Test; import junit.framework.TestSuite; import junit.textui.TestRunner; import org.apache.commons.collections.ResettableListIterator; /** * Tests the ReverseListIterator. * * @version $Revision: $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ */ public class TestReverseListIterator extends AbstractTestListIterator { protected String[] testArray = { "One", "Two", "Three", "Four" }; public static void main(String args[]) { String[] testCaseName = { TestReverseListIterator.class.getName() }; TestRunner.main(testCaseName); } public static Test suite() { return new TestSuite(TestReverseListIterator.class); } public TestReverseListIterator(String testName) { super(testName); } public ListIterator makeEmptyListIterator() { List list = new ArrayList(); return new ReverseListIterator(list); } public ListIterator makeFullListIterator() { List list = new ArrayList(Arrays.asList(testArray)); return new ReverseListIterator(list); } // overrides //----------------------------------------------------------------------- public void testEmptyListIteratorIsIndeedEmpty() { ListIterator it = makeEmptyListIterator(); assertEquals(false, it.hasNext()); assertEquals(-1, it.nextIndex()); // reversed index assertEquals(false, it.hasPrevious()); assertEquals(0, it.previousIndex()); // reversed index // 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) { } } 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()); // this had to be commented out, as there is a bug in the JDK before JDK1.5 // where calling previous at the start of an iterator would push the cursor // back to an invalid negative value // 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, list.size() - i - 2, it.nextIndex()); // reversed index assertEquals(list.size() - i - 1, it.previousIndex()); // reversed index 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) { } } //----------------------------------------------------------------------- public void testReverse() { ListIterator it = makeFullListIterator(); assertEquals(true, it.hasNext()); assertEquals(3, it.nextIndex()); assertEquals(false, it.hasPrevious()); assertEquals(4, it.previousIndex()); assertEquals("Four", it.next()); assertEquals(2, it.nextIndex()); assertEquals(true, it.hasNext()); assertEquals(3, it.previousIndex()); assertEquals(true, it.hasPrevious()); assertEquals("Three", it.next()); assertEquals(true, it.hasNext()); assertEquals(1, it.nextIndex()); assertEquals(true, it.hasPrevious()); assertEquals(2, it.previousIndex()); assertEquals("Two", it.next()); assertEquals(true, it.hasNext()); assertEquals(0, it.nextIndex()); assertEquals(true, it.hasPrevious()); assertEquals(1, it.previousIndex()); assertEquals("One", it.next()); assertEquals(false, it.hasNext()); assertEquals(-1, it.nextIndex()); assertEquals(true, it.hasPrevious()); assertEquals(0, it.previousIndex()); assertEquals("One", it.previous()); assertEquals("Two", it.previous()); assertEquals("Three", it.previous()); assertEquals("Four", it.previous()); } public void testReset() { ResettableListIterator it = (ResettableListIterator) makeFullListIterator(); assertEquals("Four", it.next()); it.reset(); assertEquals("Four", it.next()); it.next(); it.next(); it.reset(); assertEquals("Four", it.next()); } } ././@LongLink0000000000000000000000000000015700000000000011570 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/iterators/TestSingletonIterator.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/iterators/TestSingletonIte0000644000175000017500000000715710777673354032610 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.iterators; import java.util.Iterator; import java.util.NoSuchElementException; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.collections.ResettableIterator; /** * Tests the SingletonIterator to ensure that the next() method will actually * perform the iteration rather than the hasNext() method. * * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author James Strachan */ 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()); } } ././@LongLink0000000000000000000000000000016000000000000011562 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/iterators/TestSingletonIterator2.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/iterators/TestSingletonIte0000644000175000017500000000647610777673354032613 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.iterators; import java.util.Iterator; import java.util.NoSuchElementException; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.collections.ResettableIterator; /** * Tests the SingletonIterator to ensure that the next() method will actually * perform the iteration rather than the hasNext() method. * * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author James Strachan */ 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()); } } ././@LongLink0000000000000000000000000000016300000000000011565 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/iterators/TestSingletonListIterator.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/iterators/TestSingletonLis0000644000175000017500000001212610777673354032606 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.iterators; import java.util.ListIterator; import java.util.NoSuchElementException; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.collections.ResettableListIterator; /** * Tests the SingletonListIterator. * * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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()); } } ././@LongLink0000000000000000000000000000016200000000000011564 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/iterators/TestUniqueFilterIterator.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/iterators/TestUniqueFilter0000644000175000017500000000600710777673354032611 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.iterators; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import junit.framework.Test; import junit.framework.TestSuite; /** * Tests the UniqueFilterIterator class. * * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author James Strachan * @author Mauricio S. Moura * @author Morgan Delagrange * @author Stephen Colebourne */ 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())); } } } ././@LongLink0000000000000000000000000000016200000000000011564 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/iterators/TestUnmodifiableIterator.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/iterators/TestUnmodifiable0000644000175000017500000000513210777673354032571 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.iterators; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.List; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.collections.Unmodifiable; /** * Tests the UnmodifiableIterator. * * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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) {} } } ././@LongLink0000000000000000000000000000016600000000000011570 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/iterators/TestUnmodifiableListIterator.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/iterators/TestUnmodifiable0000644000175000017500000000547210777673354032600 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.iterators; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.ListIterator; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.collections.Unmodifiable; /** * Tests the UnmodifiableListIterator. * * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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) {} } } ././@LongLink0000000000000000000000000000016500000000000011567 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/iterators/TestUnmodifiableMapIterator.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/iterators/TestUnmodifiable0000644000175000017500000000613410777673354032574 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.iterators; import java.util.HashMap; import java.util.Map; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.collections.BidiMap; import org.apache.commons.collections.MapIterator; import org.apache.commons.collections.Unmodifiable; import org.apache.commons.collections.bidimap.DualHashBidiMap; /** * Tests the UnmodifiableMapIterator. * * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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) {} } } ././@LongLink0000000000000000000000000000017400000000000011567 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/iterators/TestUnmodifiableOrderedMapIterator.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/iterators/TestUnmodifiable0000644000175000017500000000655310777673354032601 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.iterators; import java.util.HashMap; import java.util.Map; import java.util.TreeMap; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.collections.MapIterator; import org.apache.commons.collections.OrderedMap; import org.apache.commons.collections.OrderedMapIterator; import org.apache.commons.collections.Unmodifiable; import org.apache.commons.collections.map.ListOrderedMap; /** * Tests the UnmodifiableOrderedMapIterator. * * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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) {} } } libcommons-collections3-java.orig/src/test/org/apache/commons/collections/keyvalue/0000755000175000017500000000000011010124151027157 5ustar godgod././@LongLink0000000000000000000000000000015500000000000011566 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/keyvalue/AbstractTestMapEntry.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/keyvalue/AbstractTestMapEn0000644000175000017500000001250010777673425032464 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.keyvalue; import java.util.HashMap; import java.util.Map; import junit.framework.TestCase; /** * 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. * * @since Commons Collections 3.0 * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Neil O'Toole */ 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())); } } libcommons-collections3-java.orig/src/test/org/apache/commons/collections/keyvalue/TestAll.java0000644000175000017500000000356510777673425031443 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.keyvalue; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * Entry point for key-value test cases. * * @since Commons Collections 3.0 * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Neil O'Toole * @author Stephen Colebourne */ 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; } } ././@LongLink0000000000000000000000000000015400000000000011565 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/keyvalue/TestDefaultKeyValue.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/keyvalue/TestDefaultKeyVal0000644000175000017500000001465510777673425032515 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.keyvalue; import java.util.HashMap; import java.util.Map; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * Test the DefaultKeyValue class. * * @since Commons Collections 3.0 * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Neil O'Toole */ 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()); } } ././@LongLink0000000000000000000000000000015400000000000011565 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/keyvalue/TestDefaultMapEntry.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/keyvalue/TestDefaultMapEnt0000644000175000017500000000667210777673425032506 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.keyvalue; import java.util.Map; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.collections.KeyValue; /** * Test the DefaultMapEntry class. * * @since Commons Collections 3.0 * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Neil O'Toole */ 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."); } } } ././@LongLink0000000000000000000000000000014500000000000011565 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/keyvalue/TestMultiKey.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/keyvalue/TestMultiKey.java0000644000175000017500000002004710777673425032470 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.keyvalue; import java.util.Arrays; import junit.framework.Assert; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * Unit tests for {@link org.apache.commons.collections.MultiKey}. * * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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); } } ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/keyvalue/TestTiedMapEntry.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/keyvalue/TestTiedMapEntry.0000644000175000017500000000605110777673425032427 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.keyvalue; import java.util.HashMap; import java.util.Map; import junit.framework.Test; import junit.framework.TestSuite; /** * Test the TiedMapEntry class. * * @since Commons Collections 3.0 * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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()); } } ././@LongLink0000000000000000000000000000016100000000000011563 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/keyvalue/TestUnmodifiableMapEntry.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/keyvalue/TestUnmodifiableM0000644000175000017500000000753510777673425032527 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.keyvalue; import java.util.Map; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.collections.KeyValue; import org.apache.commons.collections.Unmodifiable; /** * Test the UnmodifiableMapEntry class. * * @since Commons Collections 3.0 * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Neil O'Toole */ 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) {} } } libcommons-collections3-java.orig/src/test/org/apache/commons/collections/list/0000755000175000017500000000000011010124151026305 5ustar godgod././@LongLink0000000000000000000000000000014500000000000011565 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/list/AbstractTestList.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/list/AbstractTestList.java0000644000175000017500000012604110777673326032453 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.list; import java.io.IOException; import java.io.Serializable; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.AbstractCollection; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.ConcurrentModificationException; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.NoSuchElementException; import org.apache.commons.collections.BulkTest; import org.apache.commons.collections.collection.AbstractTestCollection; import org.apache.commons.collections.iterators.AbstractTestListIterator; /** * 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. * * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Rodney Waldhoff * @author Paul Jack * @author Stephen Colebourne * @author Neil O'Toole */ public abstract class AbstractTestList extends AbstractTestCollection { /** * JUnit constructor. * * @param testName the test class name */ public AbstractTestList(String testName) { super(testName); } //----------------------------------------------------------------------- /** * Returns true if the collections 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 testListListIteratorPreviousRemoveNext() { if (isRemoveSupported() == false) return; resetFull(); if (collection.size() < 4) return; ListIterator it = getList().listIterator(); Object zero = it.next(); Object one = it.next(); Object two = it.next(); Object two2 = it.previous(); Object one2 = it.previous(); assertEquals(one, one2); assertEquals(two, two2); assertEquals(zero, getList().get(0)); assertEquals(one, getList().get(1)); assertEquals(two, getList().get(2)); it.remove(); // removed element at index 1 (one) assertEquals(zero, getList().get(0)); assertEquals(two, getList().get(1)); Object two3 = it.next(); // do next after remove assertEquals(two, two3); assertEquals(collection.size() > 2, it.hasNext()); assertEquals(true, it.hasPrevious()); } /** * Tests remove on list iterator is correct. */ public void testListListIteratorPreviousRemovePrevious() { if (isRemoveSupported() == false) return; resetFull(); if (collection.size() < 4) return; ListIterator it = getList().listIterator(); Object zero = it.next(); Object one = it.next(); Object two = it.next(); Object two2 = it.previous(); Object one2 = it.previous(); assertEquals(one, one2); assertEquals(two, two2); assertEquals(zero, getList().get(0)); assertEquals(one, getList().get(1)); assertEquals(two, getList().get(2)); it.remove(); // removed element at index 1 (one) assertEquals(zero, getList().get(0)); assertEquals(two, getList().get(1)); Object zero3 = it.previous(); // do previous after remove assertEquals(zero, zero3); assertEquals(false, it.hasPrevious()); assertEquals(collection.size() > 2, it.hasNext()); } /** * Tests remove on list iterator is correct. */ public void testListListIteratorNextRemoveNext() { if (isRemoveSupported() == false) return; resetFull(); if (collection.size() < 4) return; ListIterator it = getList().listIterator(); Object zero = it.next(); Object one = it.next(); Object two = it.next(); assertEquals(zero, getList().get(0)); assertEquals(one, getList().get(1)); assertEquals(two, getList().get(2)); Object three = getList().get(3); it.remove(); // removed element at index 2 (two) assertEquals(zero, getList().get(0)); assertEquals(one, getList().get(1)); Object three2 = it.next(); // do next after remove assertEquals(three, three2); assertEquals(collection.size() > 3, it.hasNext()); assertEquals(true, it.hasPrevious()); } /** * Tests remove on list iterator is correct. */ public void testListListIteratorNextRemovePrevious() { if (isRemoveSupported() == false) return; resetFull(); if (collection.size() < 4) return; ListIterator it = getList().listIterator(); Object zero = it.next(); Object one = it.next(); Object two = it.next(); assertEquals(zero, getList().get(0)); assertEquals(one, getList().get(1)); assertEquals(two, getList().get(2)); it.remove(); // removed element at index 2 (two) assertEquals(zero, getList().get(0)); assertEquals(one, getList().get(1)); Object one2 = it.previous(); // do previous after remove assertEquals(one, one2); assertEquals(true, it.hasNext()); assertEquals(true, it.hasPrevious()); } //----------------------------------------------------------------------- /** * 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. */ 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. */ 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; public 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(); } } } ././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/list/TestAbstractLinkedList.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/list/TestAbstractLinkedLis0000644000175000017500000001525110777673326032476 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.list; import java.util.Arrays; /** * Test case for {@link AbstractLinkedList}. * * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Rich Dougherty * @author David Hay * @author Phil Steitz */ 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)); } } } } libcommons-collections3-java.orig/src/test/org/apache/commons/collections/list/TestAll.java0000644000175000017500000000422610777673326030564 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.list; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * Entry point for tests. * * @since Commons Collections 3.0 * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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(TestGrowthList.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; } } ././@LongLink0000000000000000000000000000015500000000000011566 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/list/TestCursorableLinkedList.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/list/TestCursorableLinkedL0000644000175000017500000013714310777673326032505 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.list; import java.util.ArrayList; import java.util.ConcurrentModificationException; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.NoSuchElementException; import junit.framework.Test; import org.apache.commons.collections.BulkTest; /** * Test class. * * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Rodney Waldhoff * @author Simon Kitching */ 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 testInternalState_CursorNextNextPreviousRemoveIndex1ByList() { list.add("A"); list.add("B"); list.add("C"); CursorableLinkedList.Cursor c1 = list.cursor(); assertEquals("A", c1.next()); assertEquals("B", c1.next()); assertEquals("B", c1.previous()); assertEquals("B", list.remove(1)); assertEquals(true, c1.nextIndexValid); assertEquals(1, c1.nextIndex); assertEquals(true, c1.currentRemovedByAnother); assertEquals(null, c1.current); assertEquals("C", c1.next.value); assertEquals("[A, C]", list.toString()); c1.remove(); // works ok assertEquals("[A, C]", list.toString()); try { c1.remove(); fail(); } catch (IllegalStateException ex) {} } public void testInternalState_CursorNextRemoveIndex1ByList() { list.add("A"); list.add("B"); list.add("C"); CursorableLinkedList.Cursor c1 = list.cursor(); assertEquals("A", c1.next()); assertEquals("B", list.remove(1)); assertEquals(true, c1.nextIndexValid); assertEquals(1, c1.nextIndex); assertEquals(false, c1.currentRemovedByAnother); assertEquals("A", c1.current.value); assertEquals("C", c1.next.value); assertEquals("[A, C]", list.toString()); c1.remove(); // works ok assertEquals("[C]", list.toString()); try { c1.remove(); fail(); } catch (IllegalStateException ex) {} } public void testInternalState_CursorNextNextRemoveIndex1ByList() { list.add("A"); list.add("B"); list.add("C"); CursorableLinkedList.Cursor c1 = list.cursor(); assertEquals("A", c1.next()); assertEquals("B", c1.next()); assertEquals("B", list.remove(1)); assertEquals(true, c1.nextIndexValid); assertEquals(1, c1.nextIndex); assertEquals(true, c1.currentRemovedByAnother); assertEquals(null, c1.current); assertEquals("C", c1.next.value); assertEquals("[A, C]", list.toString()); c1.remove(); // works ok assertEquals("[A, C]", list.toString()); try { c1.remove(); fail(); } catch (IllegalStateException ex) {} } public void testInternalState_CursorNextNextNextRemoveIndex1ByList() { list.add("A"); list.add("B"); list.add("C"); list.add("D"); CursorableLinkedList.Cursor c1 = list.cursor(); assertEquals("A", c1.next()); assertEquals("B", c1.next()); assertEquals("C", c1.next()); assertEquals("B", list.remove(1)); assertEquals(false, c1.nextIndexValid); assertEquals(false, c1.currentRemovedByAnother); assertEquals("C", c1.current.value); assertEquals("D", c1.next.value); assertEquals("[A, C, D]", list.toString()); c1.remove(); // works ok assertEquals("[A, D]", list.toString()); try { c1.remove(); fail(); } catch (IllegalStateException ex) {} } //----------------------------------------------------------------------- public void testInternalState_CursorNextNextPreviousRemoveByIterator() { list.add("A"); list.add("B"); list.add("C"); CursorableLinkedList.Cursor c1 = list.cursor(); assertEquals("A", c1.next()); assertEquals("B", c1.next()); assertEquals("B", c1.previous()); c1.remove(); assertEquals(true, c1.nextIndexValid); assertEquals(1, c1.nextIndex); assertEquals(false, c1.currentRemovedByAnother); assertEquals(null, c1.current); assertEquals("C", c1.next.value); assertEquals("[A, C]", list.toString()); try { c1.remove(); fail(); } catch (IllegalStateException ex) {} } public void testInternalState_CursorNextNextRemoveByIterator() { list.add("A"); list.add("B"); list.add("C"); CursorableLinkedList.Cursor c1 = list.cursor(); assertEquals("A", c1.next()); assertEquals("B", c1.next()); c1.remove(); assertEquals(true, c1.nextIndexValid); assertEquals(1, c1.nextIndex); assertEquals(false, c1.currentRemovedByAnother); assertEquals(null, c1.current); assertEquals("C", c1.next.value); assertEquals("[A, C]", list.toString()); try { c1.remove(); fail(); } catch (IllegalStateException ex) {} } //----------------------------------------------------------------------- public void testInternalState_CursorNextNextPreviousAddIndex1ByList() { list.add("A"); list.add("B"); list.add("C"); CursorableLinkedList.Cursor c1 = list.cursor(); assertEquals("A", c1.next()); assertEquals("B", c1.next()); assertEquals("B", c1.previous()); list.add(1, "Z"); assertEquals(true, c1.nextIndexValid); assertEquals(1, c1.nextIndex); assertEquals("B", c1.current.value); assertEquals("Z", c1.next.value); assertEquals("[A, Z, B, C]", list.toString()); c1.remove(); // works ok assertEquals("[A, Z, C]", list.toString()); try { c1.remove(); fail(); } catch (IllegalStateException ex) {} } public void testInternalState_CursorNextAddIndex1ByList() { list.add("A"); list.add("B"); list.add("C"); CursorableLinkedList.Cursor c1 = list.cursor(); assertEquals("A", c1.next()); list.add(1, "Z"); assertEquals(true, c1.nextIndexValid); assertEquals(1, c1.nextIndex); assertEquals("A", c1.current.value); assertEquals("Z", c1.next.value); assertEquals("[A, Z, B, C]", list.toString()); c1.remove(); // works ok assertEquals("[Z, B, C]", list.toString()); try { c1.remove(); fail(); } catch (IllegalStateException ex) {} } public void testInternalState_CursorNextNextAddIndex1ByList() { list.add("A"); list.add("B"); list.add("C"); CursorableLinkedList.Cursor c1 = list.cursor(); assertEquals("A", c1.next()); assertEquals("B", c1.next()); list.add(1, "Z"); assertEquals(false, c1.nextIndexValid); assertEquals("B", c1.current.value); assertEquals("C", c1.next.value); assertEquals("[A, Z, B, C]", list.toString()); c1.remove(); // works ok assertEquals("[A, Z, C]", list.toString()); try { c1.remove(); fail(); } catch (IllegalStateException ex) {} } //----------------------------------------------------------------------- public void testInternalState_CursorNextNextPreviousAddByIterator() { list.add("A"); list.add("B"); list.add("C"); CursorableLinkedList.Cursor c1 = list.cursor(); assertEquals("A", c1.next()); assertEquals("B", c1.next()); assertEquals("B", c1.previous()); c1.add("Z"); assertEquals(true, c1.nextIndexValid); assertEquals(2, c1.nextIndex); assertEquals(null, c1.current); assertEquals("B", c1.next.value); assertEquals("[A, Z, B, C]", list.toString()); try { c1.remove(); fail(); } catch (IllegalStateException ex) {} } public void testInternalState_CursorNextNextAddByIterator() { list.add("A"); list.add("B"); list.add("C"); CursorableLinkedList.Cursor c1 = list.cursor(); assertEquals("A", c1.next()); assertEquals("B", c1.next()); c1.add("Z"); assertEquals(true, c1.nextIndexValid); assertEquals(3, c1.nextIndex); assertEquals(false, c1.currentRemovedByAnother); assertEquals(null, c1.current); assertEquals("C", c1.next.value); assertEquals("[A, B, Z, C]", list.toString()); try { c1.remove(); fail(); } catch (IllegalStateException ex) {} } //----------------------------------------------------------------------- public void testInternalState_CursorNextNextRemoveByListSetByIterator() { list.add("A"); list.add("B"); list.add("C"); CursorableLinkedList.Cursor c1 = list.cursor(); assertEquals("A", c1.next()); assertEquals("B", c1.next()); list.remove(1); assertEquals(true, c1.nextIndexValid); assertEquals(1, c1.nextIndex); assertEquals(null, c1.current); assertEquals("C", c1.next.value); assertEquals("[A, C]", list.toString()); try { c1.set("Z"); fail(); } catch (IllegalStateException ex) {} } //----------------------------------------------------------------------- public void testInternalState_CursorNextNextPreviousSetByIterator() { list.add("A"); list.add("B"); list.add("C"); CursorableLinkedList.Cursor c1 = list.cursor(); assertEquals("A", c1.next()); assertEquals("B", c1.next()); assertEquals("B", c1.previous()); c1.set("Z"); assertEquals(true, c1.nextIndexValid); assertEquals(1, c1.nextIndex); assertEquals("Z", c1.current.value); assertEquals("Z", c1.next.value); assertEquals("[A, Z, C]", list.toString()); c1.remove(); // works ok assertEquals("[A, C]", list.toString()); try { c1.remove(); fail(); } catch (IllegalStateException ex) {} } public void testInternalState_CursorNextNextSetByIterator() { list.add("A"); list.add("B"); list.add("C"); CursorableLinkedList.Cursor c1 = list.cursor(); assertEquals("A", c1.next()); assertEquals("B", c1.next()); c1.set("Z"); assertEquals(true, c1.nextIndexValid); assertEquals(2, c1.nextIndex); assertEquals("Z", c1.current.value); assertEquals("C", c1.next.value); assertEquals("[A, Z, C]", list.toString()); c1.remove(); // works ok assertEquals("[A, C]", list.toString()); try { c1.remove(); fail(); } catch (IllegalStateException ex) {} } //----------------------------------------------------------------------- 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]); } } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/list/TestFixedSizeList.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/list/TestFixedSizeList.jav0000644000175000017500000000511510777673326032437 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.list; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import junit.framework.Test; import junit.framework.TestSuite; /** * Extension of {@link TestList} for exercising the {@link FixedSizeList} * implementation. * * @since Commons Collections 3.0 * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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/collections/data/test/FixedSizeList.emptyCollection.version3.1.obj"); // resetFull(); // writeExternalFormToDisk((java.io.Serializable) collection, "D:/dev/collections/data/test/FixedSizeList.fullCollection.version3.1.obj"); // } } libcommons-collections3-java.orig/src/test/org/apache/commons/collections/list/TestGrowthList.java0000644000175000017500000001321610777673326032161 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.list; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import junit.framework.Test; import junit.framework.TestSuite; /** * Extension of {@link TestList} for exercising the {@link GrowthList}. * * @since Commons Collections 3.2 * @version $Revision: 155406 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ public class TestGrowthList extends AbstractTestList { public TestGrowthList(String testName) { super(testName); } public static Test suite() { return new TestSuite(TestGrowthList.class); } public static void main(String args[]) { String[] testCaseName = { TestGrowthList.class.getName()}; junit.textui.TestRunner.main(testCaseName); } public List makeEmptyList() { return new GrowthList(); } public List makeFullList() { List list = new ArrayList(); list.addAll(Arrays.asList(getFullElements())); return GrowthList.decorate(list); } //----------------------------------------------------------------------- public void testGrowthAdd() { Integer one = new Integer(1); GrowthList grower = new GrowthList(); assertEquals(0, grower.size()); grower.add(1, one); assertEquals(2, grower.size()); assertEquals(null, grower.get(0)); assertEquals(one, grower.get(1)); } public void testGrowthAddAll() { Integer one = new Integer(1); Integer two = new Integer(2); Collection coll = new ArrayList(); coll.add(one); coll.add(two); GrowthList grower = new GrowthList(); assertEquals(0, grower.size()); grower.addAll(1, coll); assertEquals(3, grower.size()); assertEquals(null, grower.get(0)); assertEquals(one, grower.get(1)); assertEquals(two, grower.get(2)); } public void testGrowthSet1() { Integer one = new Integer(1); GrowthList grower = new GrowthList(); assertEquals(0, grower.size()); grower.set(1, one); assertEquals(2, grower.size()); assertEquals(null, grower.get(0)); assertEquals(one, grower.get(1)); } public void testGrowthSet2() { Integer one = new Integer(1); GrowthList grower = new GrowthList(); assertEquals(0, grower.size()); grower.set(0, one); assertEquals(1, grower.size()); assertEquals(one, grower.get(0)); } //----------------------------------------------------------------------- /** * Override. */ public void testListAddByIndexBoundsChecking() { List list; Object element = getOtherElements()[0]; try { list = makeEmptyList(); list.add(-1, element); fail("List.add should throw IndexOutOfBoundsException [-1]"); } catch (IndexOutOfBoundsException e) { // expected } } /** * Override. */ public void testListAddByIndexBoundsChecking2() { List list; Object element = getOtherElements()[0]; try { list = makeFullList(); list.add(-1, element); fail("List.add should throw IndexOutOfBoundsException [-1]"); } catch (IndexOutOfBoundsException e) { // expected } } /** * Override. */ public void testListSetByIndexBoundsChecking() { List list = makeEmptyList(); Object element = getOtherElements()[0]; try { list.set(-1, element); fail("List.set should throw IndexOutOfBoundsException [-1]"); } catch (IndexOutOfBoundsException e) { // expected } } /** * Override. */ public void testListSetByIndexBoundsChecking2() { List list = makeFullList(); Object element = getOtherElements()[0]; try { list.set(-1, element); fail("List.set should throw IndexOutOfBoundsException [-1]"); } catch(IndexOutOfBoundsException e) { // expected } } //----------------------------------------------------------------------- public String getCompatibilityVersion() { return "3.2"; } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk((java.io.Serializable) collection, "C:/commons/collections/data/test/GrowthList.emptyCollection.version3.2.obj"); // resetFull(); // writeExternalFormToDisk((java.io.Serializable) collection, "C:/commons/collections/data/test/GrowthList.fullCollection.version3.2.obj"); // } } ././@LongLink0000000000000000000000000000015600000000000011567 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/list/TestNodeCachingLinkedList.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/list/TestNodeCachingLinked0000644000175000017500000001301610777673326032422 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.list; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import junit.framework.Test; import org.apache.commons.collections.BulkTest; /** * Test class for NodeCachingLinkedList, a performance optimised LinkedList. * * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Jeff Varszegi * @author Phil Steitz */ 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/collections/data/test/NodeCachingLinkedList.emptyCollection.version3.obj"); // resetFull(); // writeExternalFormToDisk((java.io.Serializable) collection, // "D:/dev/collections/data/test/NodeCachingLinkedList.fullCollection.version3.obj"); // } } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/list/TestPredicatedList.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/list/TestPredicatedList.ja0000644000175000017500000001250510777673326032424 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.list; import java.util.ArrayList; import java.util.List; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.collections.Predicate; import org.apache.commons.collections.PredicateUtils; /** * Extension of {@link TestList} for exercising the * {@link PredicatedList} implementation. * * @since Commons Collections 3.0 * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Phil Steitz */ 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/collections/data/test/PredicatedList.emptyCollection.version3.1.obj"); // resetFull(); // writeExternalFormToDisk((java.io.Serializable) collection, "D:/dev/collections/data/test/PredicatedList.fullCollection.version3.1.obj"); // } } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/list/TestSetUniqueList.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/list/TestSetUniqueList.jav0000644000175000017500000003226710777673326032477 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.list; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.ListIterator; import junit.framework.Test; import junit.framework.TestSuite; import junit.textui.TestRunner; /** * JUnit tests. * * @since Commons Collections 3.0 * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Matthew Hawthorne * @author Tom Dunham */ 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 void testUniqueListReInsert() { List l = SetUniqueList.decorate(new LinkedList()); l.add(new Object()); l.add(new Object()); Object a = l.get(0); // duplicate is removed l.set(0, l.get(1)); assertEquals(1, l.size()); // old object is added back in l.add(1, a); assertEquals(2, l.size()); } public void testUniqueListDoubleInsert() { List l = SetUniqueList.decorate(new LinkedList()); l.add(new Object()); l.add(new Object()); // duplicate is removed l.set(0, l.get(1)); assertEquals(1, l.size()); // duplicate should be removed again l.add(1, l.get(0)); assertEquals(1, l.size()); } public void testSetDownwardsInList() { /* * Checks the following semantics * [a,b] * set(0,b): [b]->a * So UniqList contains [b] and a is returned */ ArrayList l = new ArrayList(); HashSet s = new HashSet(); final SetUniqueList ul = new SetUniqueList(l, s); Object a = new Object(); Object b = new Object(); ul.add(a); ul.add(b); assertEquals(a, l.get(0)); assertEquals(b, l.get(1)); assertTrue(s.contains(a)); assertTrue(s.contains(b)); assertEquals(a, ul.set(0, b)); assertEquals(1, s.size()); assertEquals(1, l.size()); assertEquals(b, l.get(0)); assertTrue(s.contains(b)); assertFalse(s.contains(a)); } public void testSetInBiggerList() { /* * Checks the following semantics * [a,b,c] * set(0,b): [b,c]->a * So UniqList contains [b,c] and a is returned */ ArrayList l = new ArrayList(); HashSet s = new HashSet(); final SetUniqueList ul = new SetUniqueList(l, s); Object a = new Object(); Object b = new Object(); Object c = new Object(); ul.add(a); ul.add(b); ul.add(c); assertEquals(a, l.get(0)); assertEquals(b, l.get(1)); assertEquals(c, l.get(2)); assertTrue(s.contains(a)); assertTrue(s.contains(b)); assertTrue(s.contains(c)); assertEquals(a, ul.set(0, b)); assertEquals(2, s.size()); assertEquals(2, l.size()); assertEquals(b, l.get(0)); assertEquals(c, l.get(1)); assertFalse(s.contains(a)); assertTrue(s.contains(b)); assertTrue(s.contains(c)); } public void testSetUpwardsInList() { /* * Checks the following semantics * [a,b,c] * set(1,a): [a,c]->b * So UniqList contains [a,c] and b is returned */ ArrayList l = new ArrayList(); HashSet s = new HashSet(); final SetUniqueList ul = new SetUniqueList(l, s); Object a = new String("A"); Object b = new String("B"); Object c = new String("C"); ul.add(a); ul.add(b); ul.add(c); assertEquals(a, l.get(0)); assertEquals(b, l.get(1)); assertEquals(c, l.get(2)); assertTrue(s.contains(a)); assertTrue(s.contains(b)); assertTrue(s.contains(c)); assertEquals(b, ul.set(1, a)); assertEquals(2, s.size()); assertEquals(2, l.size()); assertEquals(a, l.get(0)); assertEquals(c, l.get(1)); assertTrue(s.contains(a)); assertFalse(s.contains(b)); assertTrue(s.contains(c)); } //----------------------------------------------------------------------- public String getCompatibilityVersion() { return "3.1"; } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk((java.io.Serializable) collection, "D:/dev/collections/data/test/SetUniqueList.emptyCollection.version3.1.obj"); // resetFull(); // writeExternalFormToDisk((java.io.Serializable) collection, "D:/dev/collections/data/test/SetUniqueList.fullCollection.version3.1.obj"); // } } ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/list/TestSynchronizedList.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/list/TestSynchronizedList.0000644000175000017500000000457610777673326032535 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.list; import java.util.ArrayList; import java.util.Collection; import java.util.List; import junit.framework.Test; import junit.framework.TestSuite; /** * Extension of {@link TestList} for exercising the {@link SynchronizedList} * implementation. * * @since Commons Collections 3.1 * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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/collections/data/test/SynchronizedList.emptyCollection.version3.1.obj"); // resetFull(); // writeExternalFormToDisk((java.io.Serializable) collection, "D:/dev/collections/data/test/SynchronizedList.fullCollection.version3.1.obj"); // } } ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/list/TestTransformedList.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/list/TestTransformedList.j0000644000175000017500000001124010777673326032476 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.list; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.ListIterator; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.collections.collection.TestTransformedCollection; /** * Extension of {@link TestList} for exercising the {@link TransformedList} * implementation. * * @since Commons Collections 3.0 * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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/collections/data/test/TransformedList.emptyCollection.version3.1.obj"); // resetFull(); // writeExternalFormToDisk((java.io.Serializable) collection, "D:/dev/collections/data/test/TransformedList.fullCollection.version3.1.obj"); // } } libcommons-collections3-java.orig/src/test/org/apache/commons/collections/list/TestTreeList.java0000644000175000017500000001724410777673326031613 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.list; import java.util.List; import java.util.ListIterator; import junit.framework.Test; import org.apache.commons.collections.BulkTest; /** * JUnit tests * * @since Commons Collections 3.1 * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Joerg Schmuecker */ 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) { 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"); // } public void testBug35258() { Object objectToRemove = new Integer(3); List treelist = new TreeList(); treelist.add(new Integer(0)); treelist.add(new Integer(1)); treelist.add(new Integer(2)); treelist.add(new Integer(3)); treelist.add(new Integer(4)); // this cause inconsistence of ListIterator() treelist.remove(objectToRemove); ListIterator li = treelist.listIterator(); assertEquals(new Integer(0), li.next()); assertEquals(new Integer(0), li.previous()); assertEquals(new Integer(0), li.next()); assertEquals(new Integer(1), li.next()); // this caused error in bug 35258 assertEquals(new Integer(1), li.previous()); assertEquals(new Integer(1), li.next()); assertEquals(new Integer(2), li.next()); assertEquals(new Integer(2), li.previous()); assertEquals(new Integer(2), li.next()); assertEquals(new Integer(4), li.next()); assertEquals(new Integer(4), li.previous()); assertEquals(new Integer(4), li.next()); assertEquals(false, li.hasNext()); } } libcommons-collections3-java.orig/src/test/org/apache/commons/collections/list/TestTypedList.java0000644000175000017500000000410110777673326031765 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.list; import java.util.ArrayList; import java.util.Collection; import java.util.List; import junit.framework.Test; import junit.framework.TestSuite; /** * Extension of {@link TestList} for exercising the {@link TypedList} * implementation. * * @since Commons Collections 3.1 * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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 } } ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/list/TestUnmodifiableList.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/list/TestUnmodifiableList.0000644000175000017500000001356310777673326032450 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.list; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; import junit.framework.Test; import junit.framework.TestSuite; /** * Extension of {@link AbstractTestList} for exercising the * {@link UnmodifiableList} implementation. * * @since Commons Collections 3.0 * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Phil Steitz */ 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/collections/data/test/UnmodifiableList.emptyCollection.version3.1.obj"); // resetFull(); // writeExternalFormToDisk((java.io.Serializable) collection, "D:/dev/collections/data/test/UnmodifiableList.fullCollection.version3.1.obj"); // } } libcommons-collections3-java.orig/src/test/org/apache/commons/collections/map/0000755000175000017500000000000011010124151026107 5ustar godgod././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/map/AbstractTestIterableMap.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/map/AbstractTestIterableMa0000644000175000017500000001300110777673423032414 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.map; import java.util.ConcurrentModificationException; import java.util.Iterator; import java.util.Map; import org.apache.commons.collections.IterableMap; import org.apache.commons.collections.BulkTest; import org.apache.commons.collections.MapIterator; import org.apache.commons.collections.iterators.AbstractTestMapIterator; /** * Abstract test class for {@link IterableMap} methods and contracts. * * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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/collections/data/test/HashedMap.emptyCollection.version3.obj"); // resetFull(); // writeExternalFormToDisk((Serializable) map, "D:/dev/collections/data/test/HashedMap.fullCollection.version3.obj"); // } } libcommons-collections3-java.orig/src/test/org/apache/commons/collections/map/AbstractTestMap.java0000644000175000017500000017565210777673423032071 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.map; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.commons.collections.AbstractTestObject; import org.apache.commons.collections.BulkTest; import org.apache.commons.collections.collection.AbstractTestCollection; import org.apache.commons.collections.set.AbstractTestSet; /** * 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: * *

              * * 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 Stephen Colebourne * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ */ 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 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 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; } // check putAll OK adding empty map to empty map resetEmpty(); assertEquals(0, map.size()); map.putAll(new HashMap()); assertEquals(0, map.size()); // check putAll OK adding empty map to non-empty map resetFull(); int size = map.size(); map.putAll(new HashMap()); assertEquals(size, map.size()); // check putAll OK adding non-empty map to empty map resetEmpty(); Map m2 = makeFullMap(); map.putAll(m2); confirmed.putAll(m2); verify(); // check putAll OK adding non-empty JDK map to empty map 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(); // check putAll OK adding non-empty JDK map to non-empty map resetEmpty(); m2 = makeConfirmedMap(); map.put(keys[0], values[0]); confirmed.put(keys[0], values[0]); verify(); for(int i = 1; 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; } } ././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/map/AbstractTestOrderedMap.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/map/AbstractTestOrderedMap0000644000175000017500000001722010777673423032440 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.map; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import java.util.TreeMap; import org.apache.commons.collections.BulkTest; import org.apache.commons.collections.MapIterator; import org.apache.commons.collections.OrderedMap; import org.apache.commons.collections.comparators.NullComparator; import org.apache.commons.collections.iterators.AbstractTestOrderedMapIterator; /** * Abstract test class for {@link OrderedMap} methods and contracts. * * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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()); } /** * 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()); 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(); } } } ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/map/AbstractTestSortedMap.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/map/AbstractTestSortedMap.0000644000175000017500000003220510777673423032372 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.map; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.SortedMap; import java.util.TreeMap; import org.apache.commons.collections.BulkTest; /** * Abstract test class for {@link java.util.SortedMap} methods and contracts. * * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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/collections/data/test/FixedSizeSortedMap.emptyCollection.version3.1.HeadMapView.obj"); // map = makeFullMap(); // writeExternalFormToDisk( // (java.io.Serializable) map, // "D:/dev/collections/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/collections/data/test/FixedSizeSortedMap.emptyCollection.version3.1.TailMapView.obj"); // map = makeFullMap(); // writeExternalFormToDisk( // (java.io.Serializable) map, // "D:/dev/collections/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/collections/data/test/TransformedSortedMap.emptyCollection.version3.1.SubMapView.obj"); // map = makeFullMap(); // writeExternalFormToDisk( // (java.io.Serializable) map, // "D:/dev/collections/data/test/TransformedSortedMap.fullCollection.version3.1.SubMapView.obj"); // } } } libcommons-collections3-java.orig/src/test/org/apache/commons/collections/map/TestAll.java0000644000175000017500000000570510777673423030367 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.map; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * Entry point for tests. * * @since Commons Collections 3.0 * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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(TestDefaultedMap.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(TestMultiValueMap.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; } } ././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/map/TestCaseInsensitiveMap.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/map/TestCaseInsensitiveMap0000644000175000017500000001043110777673423032461 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.map; import java.util.HashMap; import java.util.Map; import java.util.Set; import junit.framework.Test; import junit.textui.TestRunner; import org.apache.commons.collections.BulkTest; /** * Tests for the {@link CaseInsensitiveMap} implementation. * * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Commons-Collections team */ 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() { 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() == 4); // 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() == 4); 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/collections/data/test/CaseInsensitiveMap.emptyCollection.version3.obj"); resetFull(); writeExternalFormToDisk((java.io.Serializable) map, "/home/phil/jakarta-commons/collections/data/test/CaseInsensitiveMap.fullCollection.version3.obj"); } */ } libcommons-collections3-java.orig/src/test/org/apache/commons/collections/map/TestCompositeMap.java0000644000175000017500000001643610777673423032262 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.map; import junit.framework.Test; import junit.framework.TestSuite; import junit.framework.Assert; import java.util.Map; import java.util.HashMap; import java.util.Collection; /** * Extension of {@link AbstractTestMap} for exercising the * {@link CompositeMap} implementation. * * @since Commons Collections 3.0 * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Brian McCallister */ 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); } } libcommons-collections3-java.orig/src/test/org/apache/commons/collections/map/TestDefaultedMap.java0000644000175000017500000001314110777673423032203 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.map; import java.util.HashMap; import java.util.Map; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.collections.Factory; import org.apache.commons.collections.FactoryUtils; import org.apache.commons.collections.Transformer; import org.apache.commons.collections.functors.ConstantFactory; /** * Extension of {@link TestMap} for exercising the * {@link DefaultedMap} implementation. * * @since Commons Collections 3.2 * @version $Revision: 155406 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ public class TestDefaultedMap extends AbstractTestMap { protected static final Factory nullFactory = FactoryUtils.nullFactory(); public TestDefaultedMap(String testName) { super(testName); } public static Test suite() { return new TestSuite(TestDefaultedMap.class); } public static void main(String args[]) { String[] testCaseName = { TestDefaultedMap.class.getName()}; junit.textui.TestRunner.main(testCaseName); } //----------------------------------------------------------------------- public Map makeEmptyMap() { return DefaultedMap.decorate(new HashMap(), nullFactory); } //----------------------------------------------------------------------- public void testMapGet() { Map map = new DefaultedMap("NULL"); assertEquals(0, map.size()); assertEquals(false, map.containsKey("NotInMap")); assertEquals("NULL", map.get("NotInMap")); map.put("Key", "Value"); assertEquals(1, map.size()); assertEquals(true, map.containsKey("Key")); assertEquals("Value", map.get("Key")); assertEquals(false, map.containsKey("NotInMap")); assertEquals("NULL", map.get("NotInMap")); } public void testMapGet2() { HashMap base = new HashMap(); Map map = DefaultedMap.decorate(base, "NULL"); assertEquals(0, map.size()); assertEquals(0, base.size()); assertEquals(false, map.containsKey("NotInMap")); assertEquals("NULL", map.get("NotInMap")); map.put("Key", "Value"); assertEquals(1, map.size()); assertEquals(1, base.size()); assertEquals(true, map.containsKey("Key")); assertEquals("Value", map.get("Key")); assertEquals(false, map.containsKey("NotInMap")); assertEquals("NULL", map.get("NotInMap")); } public void testMapGet3() { HashMap base = new HashMap(); Map map = DefaultedMap.decorate(base, ConstantFactory.getInstance("NULL")); assertEquals(0, map.size()); assertEquals(0, base.size()); assertEquals(false, map.containsKey("NotInMap")); assertEquals("NULL", map.get("NotInMap")); map.put("Key", "Value"); assertEquals(1, map.size()); assertEquals(1, base.size()); assertEquals(true, map.containsKey("Key")); assertEquals("Value", map.get("Key")); assertEquals(false, map.containsKey("NotInMap")); assertEquals("NULL", map.get("NotInMap")); } public void testMapGet4() { HashMap base = new HashMap(); Map map = DefaultedMap.decorate(base, new Transformer() { public Object transform(Object input) { if (input instanceof String) { return "NULL"; } return "NULL_OBJECT"; } }); assertEquals(0, map.size()); assertEquals(0, base.size()); assertEquals(false, map.containsKey("NotInMap")); assertEquals("NULL", map.get("NotInMap")); assertEquals("NULL_OBJECT", map.get(new Integer(0))); map.put("Key", "Value"); assertEquals(1, map.size()); assertEquals(1, base.size()); assertEquals(true, map.containsKey("Key")); assertEquals("Value", map.get("Key")); assertEquals(false, map.containsKey("NotInMap")); assertEquals("NULL", map.get("NotInMap")); assertEquals("NULL_OBJECT", map.get(new Integer(0))); } public String getCompatibilityVersion() { return "3.2"; } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk( // (java.io.Serializable) map, // "c:/commons/collections/data/test/DefaultedMap.emptyCollection.version3.2.obj"); // resetFull(); // writeExternalFormToDisk( // (java.io.Serializable) map, // "c:/commons/collections/data/test/DefaultedMap.fullCollection.version3.2.obj"); // } } libcommons-collections3-java.orig/src/test/org/apache/commons/collections/map/TestFixedSizeMap.java0000644000175000017500000000507310777673423032205 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.map; import java.util.HashMap; import java.util.Map; import junit.framework.Test; import junit.framework.TestSuite; /** * Extension of {@link AbstractTestMap} for exercising the {@link FixedSizeMap} * implementation. * * @since Commons Collections 3.0 * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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/collections/data/test/FixedSizeMap.emptyCollection.version3.1.obj"); // resetFull(); // writeExternalFormToDisk( // (java.io.Serializable) map, // "D:/dev/collections/data/test/FixedSizeMap.fullCollection.version3.1.obj"); // } } ././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/map/TestFixedSizeSortedMap.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/map/TestFixedSizeSortedMap0000644000175000017500000000574210777673423032451 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.map; import java.util.Map; import java.util.SortedMap; import java.util.TreeMap; import junit.framework.Test; import org.apache.commons.collections.BulkTest; /** * Extension of {@link TestSortedMap} for exercising the {@link FixedSizeSortedMap} * implementation. * * @since Commons Collections 3.0 * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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/collections/data/test/FixedSizeSortedMap.emptyCollection.version3.1.obj"); // resetFull(); // writeExternalFormToDisk( // (java.io.Serializable) map, // "D:/dev/collections/data/test/FixedSizeSortedMap.fullCollection.version3.1.obj"); // } } libcommons-collections3-java.orig/src/test/org/apache/commons/collections/map/TestFlat3Map.java0000644000175000017500000002325110777673423031262 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.map; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Map; import junit.framework.Test; import junit.textui.TestRunner; import org.apache.commons.collections.BulkTest; import org.apache.commons.collections.MapIterator; import org.apache.commons.collections.iterators.AbstractTestMapIterator; /** * JUnit tests. * * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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 testEquals1() { Flat3Map map1 = new Flat3Map(); map1.put("a", "testA"); map1.put("b", "testB"); Flat3Map map2 = new Flat3Map(); map2.put("a", "testB"); map2.put("b", "testA"); assertEquals(false, map1.equals(map2)); } public void testEquals2() { Flat3Map map1 = new Flat3Map(); map1.put("a", "testA"); map1.put("b", "testB"); Flat3Map map2 = new Flat3Map(); map2.put("a", "testB"); map2.put("c", "testA"); assertEquals(false, map1.equals(map2)); } 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/collections/data/test/Flat3Map.emptyCollection.version3.1.obj"); // resetFull(); // writeExternalFormToDisk( // (java.io.Serializable) map, // "D:/dev/collections/data/test/Flat3Map.fullCollection.version3.1.obj"); // } } libcommons-collections3-java.orig/src/test/org/apache/commons/collections/map/TestHashedMap.java0000644000175000017500000000506710777673423031512 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.map; import java.util.Map; import junit.framework.Test; import junit.textui.TestRunner; import org.apache.commons.collections.BulkTest; /** * JUnit tests. * * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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 testInternalState() { HashedMap map = new HashedMap(42, 0.75f); assertEquals(0.75f, map.loadFactor, 0.1f); assertEquals(0, map.size); assertEquals(64, map.data.length); assertEquals(48, map.threshold); assertEquals(0, map.modCount); } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk((java.io.Serializable) map, "D:/dev/collections/data/test/HashedMap.emptyCollection.version3.obj"); // resetFull(); // writeExternalFormToDisk((java.io.Serializable) map, "D:/dev/collections/data/test/HashedMap.fullCollection.version3.obj"); // } } libcommons-collections3-java.orig/src/test/org/apache/commons/collections/map/TestIdentityMap.java0000644000175000017500000001252110777673423032100 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.map; import java.io.IOException; import java.io.Serializable; import java.util.Iterator; import java.util.Map; import junit.framework.Test; import junit.framework.TestSuite; import junit.textui.TestRunner; import org.apache.commons.collections.AbstractTestObject; import org.apache.commons.collections.IterableMap; /** * JUnit tests. * * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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 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/collections/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/collections/data/test/IdentityMap.fullCollection.version3.obj"); // } } libcommons-collections3-java.orig/src/test/org/apache/commons/collections/map/TestLazyMap.java0000644000175000017500000000673510777673423031240 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.map; import java.util.HashMap; import java.util.Map; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.collections.Factory; import org.apache.commons.collections.FactoryUtils; /** * Extension of {@link TestMap} for exercising the * {@link LazyMap} implementation. * * @since Commons Collections 3.0 * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Phil Steitz */ 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/collections/data/test/LazyMap.emptyCollection.version3.1.obj"); // resetFull(); // writeExternalFormToDisk( // (java.io.Serializable) map, // "D:/dev/collections/data/test/LazyMap.fullCollection.version3.1.obj"); // } }././@LongLink0000000000000000000000000000014500000000000011565 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/map/TestLazySortedMap.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/map/TestLazySortedMap.java0000644000175000017500000001313010777673423032404 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.map; import java.util.Comparator; import java.util.Map; import java.util.SortedMap; import java.util.TreeMap; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.collections.Factory; import org.apache.commons.collections.FactoryUtils; import org.apache.commons.collections.Transformer; import org.apache.commons.collections.TransformerUtils; /** * Extension of {@link TestLazyMap} for exercising the * {@link LazySortedMap} implementation. * * @since Commons Collections 3.0 * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Phil Steitz */ 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/collections/data/test/LazySortedMap.emptyCollection.version3.1.obj"); // resetFull(); // writeExternalFormToDisk( // (java.io.Serializable) map, // "D:/dev/collections/data/test/LazySortedMap.fullCollection.version3.1.obj"); // } } libcommons-collections3-java.orig/src/test/org/apache/commons/collections/map/TestLinkedMap.java0000644000175000017500000002137210777673423031521 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.map; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import junit.framework.Test; import junit.textui.TestRunner; import org.apache.commons.collections.BulkTest; import org.apache.commons.collections.MapIterator; import org.apache.commons.collections.OrderedMap; import org.apache.commons.collections.ResettableIterator; import org.apache.commons.collections.list.AbstractTestList; /** * JUnit tests. * * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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/collections/data/test/LinkedMap.emptyCollection.version3.obj"); // resetFull(); // writeExternalFormToDisk((java.io.Serializable) map, "D:/dev/collections/data/test/LinkedMap.fullCollection.version3.obj"); // } } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/map/TestListOrderedMap.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/map/TestListOrderedMap.jav0000644000175000017500000003414610777673423032375 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.map; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import junit.framework.Test; import org.apache.commons.collections.BulkTest; import org.apache.commons.collections.MapIterator; import org.apache.commons.collections.list.AbstractTestList; /** * Extension of {@link TestMap} for exercising the {@link ListOrderedMap} * implementation. * * @since Commons Collections 3.0 * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Henri Yandell * @author Stephen Colebourne * @author Matt Benson */ 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 testSetValueByIndex() { resetEmpty(); ListOrderedMap lom = (ListOrderedMap) map; try { lom.setValue(0, ""); } catch (IndexOutOfBoundsException ex) {} try { lom.setValue(-1, ""); } catch (IndexOutOfBoundsException ex) {} resetFull(); lom = (ListOrderedMap) map; try { lom.setValue(-1, ""); } catch (IndexOutOfBoundsException ex) {} try { lom.setValue(lom.size(), ""); } catch (IndexOutOfBoundsException ex) {} for (int i = 0; i < lom.size(); i++) { Object value = lom.getValue(i); Object input = new Integer(i); assertEquals(value, lom.setValue(i, input)); assertEquals(input, lom.getValue(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 void testPut_intObjectObject() { resetEmpty(); ListOrderedMap lom = (ListOrderedMap) map; try { lom.put(1, "testInsert1", "testInsert1v"); fail("should not be able to insert at pos 1 in empty Map"); } catch (IndexOutOfBoundsException ex) {} try { lom.put(-1, "testInsert-1", "testInsert-1v"); fail("should not be able to insert at pos -1 in empty Map"); } catch (IndexOutOfBoundsException ex) {} // put where key doesn't exist lom.put(0, "testInsert1", "testInsert1v"); assertEquals("testInsert1v", lom.getValue(0)); lom.put("testInsertPut", "testInsertPutv"); assertEquals("testInsert1v", lom.getValue(0)); assertEquals("testInsertPutv", lom.getValue(1)); lom.put(0, "testInsert0", "testInsert0v"); assertEquals("testInsert0v", lom.getValue(0)); assertEquals("testInsert1v", lom.getValue(1)); assertEquals("testInsertPutv", lom.getValue(2)); lom.put(3, "testInsert3", "testInsert3v"); assertEquals("testInsert0v", lom.getValue(0)); assertEquals("testInsert1v", lom.getValue(1)); assertEquals("testInsertPutv", lom.getValue(2)); assertEquals("testInsert3v", lom.getValue(3)); // put in a full map resetFull(); lom = (ListOrderedMap) map; ListOrderedMap lom2 = new ListOrderedMap(); lom2.putAll(lom); lom2.put(0, "testInsert0", "testInsert0v"); assertEquals("testInsert0v", lom2.getValue(0)); for (int i = 0; i < lom.size(); i++) { assertEquals(lom2.getValue(i + 1), lom.getValue(i)); } // put where key does exist Integer i1 = new Integer(1); Integer i1b = new Integer(1); Integer i2 = new Integer(2); Integer i3 = new Integer(3); resetEmpty(); lom = (ListOrderedMap) map; lom.put(i1, "1"); lom.put(i2, "2"); lom.put(i3, "3"); lom.put(0, i1, "One"); assertEquals(3, lom.size()); assertEquals(3, lom.map.size()); assertEquals(3, lom.insertOrder.size()); assertEquals("One", lom.getValue(0)); assertSame(i1, lom.get(0)); resetEmpty(); lom = (ListOrderedMap) map; lom.put(i1, "1"); lom.put(i2, "2"); lom.put(i3, "3"); lom.put(0, i1b, "One"); assertEquals(3, lom.size()); assertEquals(3, lom.map.size()); assertEquals(3, lom.insertOrder.size()); assertEquals("One", lom.getValue(0)); assertEquals("2", lom.getValue(1)); assertEquals("3", lom.getValue(2)); assertSame(i1b, lom.get(0)); resetEmpty(); lom = (ListOrderedMap) map; lom.put(i1, "1"); lom.put(i2, "2"); lom.put(i3, "3"); lom.put(1, i1b, "One"); assertEquals(3, lom.size()); assertEquals(3, lom.map.size()); assertEquals(3, lom.insertOrder.size()); assertEquals("One", lom.getValue(0)); assertEquals("2", lom.getValue(1)); assertEquals("3", lom.getValue(2)); resetEmpty(); lom = (ListOrderedMap) map; lom.put(i1, "1"); lom.put(i2, "2"); lom.put(i3, "3"); lom.put(2, i1b, "One"); assertEquals(3, lom.size()); assertEquals(3, lom.map.size()); assertEquals(3, lom.insertOrder.size()); assertEquals("2", lom.getValue(0)); assertEquals("One", lom.getValue(1)); assertEquals("3", lom.getValue(2)); resetEmpty(); lom = (ListOrderedMap) map; lom.put(i1, "1"); lom.put(i2, "2"); lom.put(i3, "3"); lom.put(3, i1b, "One"); assertEquals(3, lom.size()); assertEquals(3, lom.map.size()); assertEquals(3, lom.insertOrder.size()); assertEquals("2", lom.getValue(0)); assertEquals("3", lom.getValue(1)); assertEquals("One", lom.getValue(2)); } //----------------------------------------------------------------------- public void testValueList_getByIndex() { resetFull(); ListOrderedMap lom = (ListOrderedMap) map; for (int i = 0; i < lom.size(); i++) { Object expected = lom.getValue(i); assertEquals(expected, lom.valueList().get(i)); } } public void testValueList_setByIndex() { resetFull(); ListOrderedMap lom = (ListOrderedMap) map; for (int i = 0; i < lom.size(); i++) { Object input = new Integer(i); Object expected = lom.getValue(i); assertEquals(expected, lom.valueList().set(i, input)); assertEquals(input, lom.getValue(i)); assertEquals(input, lom.valueList().get(i)); } } public void testValueList_removeByIndex() { resetFull(); ListOrderedMap lom = (ListOrderedMap) map; while (lom.size() > 1) { Object expected = lom.getValue(1); assertEquals(expected, lom.valueList().remove(1)); } } //----------------------------------------------------------------------- public BulkTest bulkTestKeyListView() { return new TestKeyListView(); } public BulkTest bulkTestValueListView() { return new TestValueListView(); } //----------------------------------------------------------------------- public class TestKeyListView extends AbstractTestList { TestKeyListView() { super("TestKeyListView"); } public List makeEmptyList() { return ((ListOrderedMap) TestListOrderedMap.this.makeEmptyMap()).keyList(); } public List makeFullList() { return ((ListOrderedMap) TestListOrderedMap.this.makeFullMap()).keyList(); } 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 class TestValueListView extends AbstractTestList { TestValueListView() { super("TestValueListView"); } public List makeEmptyList() { return ((ListOrderedMap) TestListOrderedMap.this.makeEmptyMap()).valueList(); } public List makeFullList() { return ((ListOrderedMap) TestListOrderedMap.this.makeFullMap()).valueList(); } public Object[] getFullElements() { return TestListOrderedMap.this.getSampleValues(); } public boolean isAddSupported() { return false; } public boolean isRemoveSupported() { return true; } public boolean isSetSupported() { return true; } 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/collections/data/test/ListOrderedMap.emptyCollection.version3.1.obj"); // resetFull(); // writeExternalFormToDisk( // (java.io.Serializable) map, // "D:/dev/collections/data/test/ListOrderedMap.fullCollection.version3.1.obj"); // } } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/map/TestListOrderedMap2.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/map/TestListOrderedMap2.ja0000644000175000017500000001510510777673423032263 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.map; import java.util.ArrayList; import java.util.List; import java.util.Map; import junit.framework.Test; import org.apache.commons.collections.BulkTest; import org.apache.commons.collections.MapIterator; import org.apache.commons.collections.list.AbstractTestList; /** * Extension of {@link TestMap} for exercising the {@link ListOrderedMap} * implementation. * * @since Commons Collections 3.1 * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Henri Yandell * @author Stephen Colebourne */ 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/collections/data/test/ListOrderedMap.emptyCollection.version3.1.obj"); // resetFull(); // writeExternalFormToDisk( // (java.io.Serializable) map, // "D:/dev/collections/data/test/ListOrderedMap.fullCollection.version3.1.obj"); // } } libcommons-collections3-java.orig/src/test/org/apache/commons/collections/map/TestLRUMap.java0000644000175000017500000004171410777673423030757 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.map; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import junit.framework.Test; import junit.textui.TestRunner; import org.apache.commons.collections.BulkTest; import org.apache.commons.collections.OrderedMap; import org.apache.commons.collections.ResettableIterator; /** * JUnit tests. * * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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; } } } //----------------------------------------------------------------------- static class SingleHashCode { private final String code; SingleHashCode(String code) { this.code = code; } public int hashCode() { // always return the same hashcode // that way, it will end up in the same bucket return 12; } public String toString() { return "SingleHashCode:" + code; } } public void testInternalState_Buckets() { if (isPutAddSupported() == false || isPutChangeSupported() == false) return; SingleHashCode one = new SingleHashCode("1"); SingleHashCode two = new SingleHashCode("2"); SingleHashCode three = new SingleHashCode("3"); SingleHashCode four = new SingleHashCode("4"); SingleHashCode five = new SingleHashCode("5"); SingleHashCode six = new SingleHashCode("6"); LRUMap map = new LRUMap(3, 1.0f); int hashIndex = map.hashIndex(map.hash(one), 4); map.put(one, "A"); map.put(two, "B"); map.put(three, "C"); assertEquals(4, map.data.length); assertEquals(3, map.size); assertEquals(null, map.header.next); assertEquals(one, map.header.after.key); // LRU assertEquals(two, map.header.after.after.key); assertEquals(three, map.header.after.after.after.key); // MRU assertEquals(three, map.data[hashIndex].key); assertEquals(two, map.data[hashIndex].next.key); assertEquals(one, map.data[hashIndex].next.next.key); map.put(four, "D"); // reuses last in next list assertEquals(4, map.data.length); assertEquals(3, map.size); assertEquals(null, map.header.next); assertEquals(two, map.header.after.key); // LRU assertEquals(three, map.header.after.after.key); assertEquals(four, map.header.after.after.after.key); // MRU assertEquals(four, map.data[hashIndex].key); assertEquals(three, map.data[hashIndex].next.key); assertEquals(two, map.data[hashIndex].next.next.key); map.get(three); assertEquals(4, map.data.length); assertEquals(3, map.size); assertEquals(null, map.header.next); assertEquals(two, map.header.after.key); // LRU assertEquals(four, map.header.after.after.key); assertEquals(three, map.header.after.after.after.key); // MRU assertEquals(four, map.data[hashIndex].key); assertEquals(three, map.data[hashIndex].next.key); assertEquals(two, map.data[hashIndex].next.next.key); map.put(five, "E"); // reuses last in next list assertEquals(4, map.data.length); assertEquals(3, map.size); assertEquals(null, map.header.next); assertEquals(four, map.header.after.key); // LRU assertEquals(three, map.header.after.after.key); assertEquals(five, map.header.after.after.after.key); // MRU assertEquals(five, map.data[hashIndex].key); assertEquals(four, map.data[hashIndex].next.key); assertEquals(three, map.data[hashIndex].next.next.key); map.get(three); map.get(five); assertEquals(4, map.data.length); assertEquals(3, map.size); assertEquals(null, map.header.next); assertEquals(four, map.header.after.key); // LRU assertEquals(three, map.header.after.after.key); assertEquals(five, map.header.after.after.after.key); // MRU assertEquals(five, map.data[hashIndex].key); assertEquals(four, map.data[hashIndex].next.key); assertEquals(three, map.data[hashIndex].next.next.key); map.put(six, "F"); // reuses middle in next list assertEquals(4, map.data.length); assertEquals(3, map.size); assertEquals(null, map.header.next); assertEquals(three, map.header.after.key); // LRU assertEquals(five, map.header.after.after.key); assertEquals(six, map.header.after.after.after.key); // MRU assertEquals(six, map.data[hashIndex].key); assertEquals(five, map.data[hashIndex].next.key); assertEquals(three, map.data[hashIndex].next.next.key); } public void testInternalState_getEntry_int() { if (isPutAddSupported() == false || isPutChangeSupported() == false) return; SingleHashCode one = new SingleHashCode("1"); SingleHashCode two = new SingleHashCode("2"); SingleHashCode three = new SingleHashCode("3"); SingleHashCode four = new SingleHashCode("4"); SingleHashCode five = new SingleHashCode("5"); SingleHashCode six = new SingleHashCode("6"); LRUMap map = new LRUMap(3, 1.0f); int hashIndex = map.hashIndex(map.hash(one), 4); map.put(one, "A"); map.put(two, "B"); map.put(three, "C"); assertEquals(one, map.getEntry(0).key); assertEquals(two, map.getEntry(1).key); assertEquals(three, map.getEntry(2).key); try { map.getEntry(-1); fail(); } catch (IndexOutOfBoundsException ex) {} try { map.getEntry(3); fail(); } catch (IndexOutOfBoundsException ex) {} } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk((java.io.Serializable) map, "D:/dev/collections/data/test/LRUMap.emptyCollection.version3.obj"); // resetFull(); // writeExternalFormToDisk((java.io.Serializable) map, "D:/dev/collections/data/test/LRUMap.fullCollection.version3.obj"); // } } libcommons-collections3-java.orig/src/test/org/apache/commons/collections/map/TestMultiKeyMap.java0000644000175000017500000005453510777673423032065 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.map; import java.util.Map; import junit.framework.Test; import junit.textui.TestRunner; import org.apache.commons.collections.BulkTest; import org.apache.commons.collections.MapIterator; import org.apache.commons.collections.keyvalue.MultiKey; /** * JUnit tests. * * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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"); } } } 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]; 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/collections/data/test/MultiKeyMap.emptyCollection.version3.1.obj"); // resetFull(); // writeExternalFormToDisk( // (java.io.Serializable) map, // "D:/dev/collections/data/test/MultiKeyMap.fullCollection.version3.1.obj"); // } } ././@LongLink0000000000000000000000000000014500000000000011565 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/map/TestMultiValueMap.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/map/TestMultiValueMap.java0000644000175000017500000003003610777673423032377 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.map; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.Map; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.apache.commons.collections.IteratorUtils; import org.apache.commons.collections.MultiMap; import org.apache.commons.collections.TestMultiHashMap; /** * TestMultiValueMap. * * @author James Carman * @author Stephen Colebourne * @since Commons Collections 3.2 */ public class TestMultiValueMap extends TestCase { public TestMultiValueMap(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); } public void testNoMappingReturnsNull() { final MultiValueMap map = createTestMap(); assertNull(map.get("whatever")); } public void testValueCollectionType() { final MultiValueMap map = createTestMap(LinkedList.class); assertTrue(map.get("one") instanceof LinkedList); } public void testMultipleValues() { final MultiValueMap map = createTestMap(HashSet.class); final HashSet expected = new HashSet(); expected.add("uno"); expected.add("un"); assertEquals(expected, map.get("one")); } public void testContainsValue() { final MultiValueMap map = createTestMap(HashSet.class); assertTrue(map.containsValue("uno")); assertTrue(map.containsValue("un")); assertTrue(map.containsValue("dos")); assertTrue(map.containsValue("deux")); assertTrue(map.containsValue("tres")); assertTrue(map.containsValue("trois")); assertFalse(map.containsValue("quatro")); } public void testKeyContainsValue() { final MultiValueMap map = createTestMap(HashSet.class); assertTrue(map.containsValue("one", "uno")); assertTrue(map.containsValue("one", "un")); assertTrue(map.containsValue("two", "dos")); assertTrue(map.containsValue("two", "deux")); assertTrue(map.containsValue("three", "tres")); assertTrue(map.containsValue("three", "trois")); assertFalse(map.containsValue("four", "quatro")); } public void testValues() { final MultiValueMap map = createTestMap(HashSet.class); final HashSet expected = new HashSet(); expected.add("uno"); expected.add("dos"); expected.add("tres"); expected.add("un"); expected.add("deux"); expected.add("trois"); final Collection c = map.values(); assertEquals(6, c.size()); assertEquals(expected, new HashSet(c)); } private MultiValueMap createTestMap() { return createTestMap(ArrayList.class); } private MultiValueMap createTestMap(Class collectionClass) { final MultiValueMap map = MultiValueMap.decorate(new HashMap(), collectionClass); map.put("one", "uno"); map.put("one", "un"); map.put("two", "dos"); map.put("two", "deux"); map.put("three", "tres"); map.put("three", "trois"); return map; } public void testKeyedIterator() { final MultiValueMap map = createTestMap(); final ArrayList actual = new ArrayList(IteratorUtils.toList(map.iterator("one"))); final ArrayList expected = new ArrayList(Arrays.asList(new String[]{"uno", "un"})); assertEquals(expected, actual); } public void testRemoveAllViaIterator() { final MultiValueMap map = createTestMap(); for(Iterator i = map.values().iterator(); i.hasNext();) { i.next(); i.remove(); } assertNull(map.get("one")); assertTrue(map.isEmpty()); } public void testRemoveAllViaKeyedIterator() { final MultiValueMap map = createTestMap(); for(Iterator i = map.iterator("one"); i.hasNext();) { i.next(); i.remove(); } assertNull(map.get("one")); assertEquals(4, map.totalSize()); } public void testTotalSizeA() { assertEquals(6, createTestMap().totalSize()); } //----------------------------------------------------------------------- public void testMapEquals() { MultiValueMap one = new MultiValueMap(); Integer value = new Integer(1); one.put("One", value); one.remove("One", value); MultiValueMap two = new MultiValueMap(); assertEquals(two, one); } //----------------------------------------------------------------------- public void testGetCollection() { MultiValueMap map = new MultiValueMap(); map.put("A", "AA"); assertSame(map.get("A"), map.getCollection("A")); } public void testTotalSize() { MultiValueMap map = new MultiValueMap(); 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() { MultiValueMap map = new MultiValueMap(); assertEquals(0, map.size()); map.put("A", "AA"); assertEquals(1, map.size()); map.put("B", "BA"); assertEquals(2, map.size()); map.put("B", "BB"); assertEquals(2, map.size()); map.put("B", "BC"); assertEquals(2, map.size()); map.remove("A"); assertEquals(2, map.size()); map.remove("B", "BC"); assertEquals(2, map.size()); } public void testSize_Key() { MultiValueMap map = new MultiValueMap(); 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() { MultiValueMap map = new MultiValueMap(); 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() { MultiValueMap map = new MultiValueMap(); 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_Map1() { MultiMap original = new MultiValueMap(); original.put("key", "object1"); original.put("key", "object2"); MultiValueMap test = new MultiValueMap(); test.put("keyA", "objectA"); test.put("key", "object0"); test.putAll(original); assertEquals(2, test.size()); assertEquals(4, test.totalSize()); assertEquals(1, test.getCollection("keyA").size()); assertEquals(3, test.getCollection("key").size()); assertEquals(true, test.containsValue("objectA")); assertEquals(true, test.containsValue("object0")); assertEquals(true, test.containsValue("object1")); assertEquals(true, test.containsValue("object2")); } public void testPutAll_Map2() { Map original = new HashMap(); original.put("keyX", "object1"); original.put("keyY", "object2"); MultiValueMap test = new MultiValueMap(); test.put("keyA", "objectA"); test.put("keyX", "object0"); test.putAll(original); assertEquals(3, test.size()); assertEquals(4, test.totalSize()); assertEquals(1, test.getCollection("keyA").size()); assertEquals(2, test.getCollection("keyX").size()); assertEquals(1, test.getCollection("keyY").size()); assertEquals(true, test.containsValue("objectA")); assertEquals(true, test.containsValue("object0")); assertEquals(true, test.containsValue("object1")); assertEquals(true, test.containsValue("object2")); } public void testPutAll_KeyCollection() { MultiValueMap map = new MultiValueMap(); 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 testRemove_KeyItem() { MultiValueMap map = new MultiValueMap(); map.put("A", "AA"); map.put("A", "AB"); map.put("A", "AC"); assertEquals(null, map.remove("C", "CA")); assertEquals(null, map.remove("A", "AD")); assertEquals("AC", map.remove("A", "AC")); assertEquals("AB", map.remove("A", "AB")); assertEquals("AA", map.remove("A", "AA")); assertEquals(new MultiValueMap(), map); } } ././@LongLink0000000000000000000000000000014500000000000011565 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/map/TestPredicatedMap.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/map/TestPredicatedMap.java0000644000175000017500000001202510777673423032352 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.map; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.collections.Predicate; import org.apache.commons.collections.PredicateUtils; /** * Extension of {@link TestMap} for exercising the * {@link PredicatedMap} implementation. * * @since Commons Collections 3.0 * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Phil Steitz */ 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/collections/data/test/PredicatedMap.emptyCollection.version3.1.obj"); // resetFull(); // writeExternalFormToDisk( // (java.io.Serializable) map, // "D:/dev/collections/data/test/PredicatedMap.fullCollection.version3.1.obj"); // } }././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/map/TestPredicatedSortedMap.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/map/TestPredicatedSortedMa0000644000175000017500000001542710777673423032444 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.map; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.SortedMap; import java.util.TreeMap; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.collections.Predicate; import org.apache.commons.collections.PredicateUtils; /** * Extension of {@link TestPredicatedMap} for exercising the * {@link PredicatedSortedMap} implementation. * * @since Commons Collections 3.0 * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Phil Steitz */ 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/collections/data/test/PredicatedSortedMap.emptyCollection.version3.1.obj"); // resetFull(); // writeExternalFormToDisk( // (java.io.Serializable) map, // "D:/dev/collections/data/test/PredicatedSortedMap.fullCollection.version3.1.obj"); // } } ././@LongLink0000000000000000000000000000015400000000000011565 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/map/TestReferenceIdentityMap.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/map/TestReferenceIdentityM0000644000175000017500000002661610777673423032470 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.map; import java.lang.ref.WeakReference; import java.util.Iterator; import java.util.Map; import junit.framework.Test; import org.apache.commons.collections.BulkTest; import org.apache.commons.collections.IterableMap; /** * Tests for ReferenceIdentityMap. * * @version $Revision: 646780 $ * * @author Paul Jack * @author Stephen Colebourne * @author Guilhem Lavaux */ 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 [collections] 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); } } */ WeakReference keyReference; WeakReference valueReference; public Map buildRefMap() { Object key = new Object(); Object value = new Object(); keyReference = new WeakReference(key); valueReference = new WeakReference(value); Map testMap = new ReferenceIdentityMap(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()); return testMap; } /** Tests whether purge values setting works */ public void testPurgeValues() throws Exception { // many thanks to Juozas Baliuka for suggesting this method Map testMap = buildRefMap(); 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 } } } libcommons-collections3-java.orig/src/test/org/apache/commons/collections/map/TestReferenceMap.java0000644000175000017500000002116010777673423032204 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.map; import java.lang.ref.WeakReference; import java.util.Map; import junit.framework.Test; import org.apache.commons.collections.BulkTest; /** * Tests for ReferenceMap. * * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Paul Jack * @author Guilhem Lavaux */ 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); } } */ WeakReference keyReference; WeakReference valueReference; public Map buildRefMap() { Object key = new Object(); Object value = new Object(); keyReference = new WeakReference(key); 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()); return testMap; } /** Tests whether purge values setting works */ public void testPurgeValues() throws Exception { // many thanks to Juozas Baliuka for suggesting this method Map testMap = buildRefMap(); 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 } } } libcommons-collections3-java.orig/src/test/org/apache/commons/collections/map/TestSingletonMap.java0000644000175000017500000001404610777673423032255 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.map; import java.util.HashMap; import java.util.Map; import junit.framework.Test; import junit.textui.TestRunner; import org.apache.commons.collections.BoundedMap; import org.apache.commons.collections.BulkTest; import org.apache.commons.collections.KeyValue; /** * JUnit tests. * * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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/collections/data/test/SingletonMap.emptyCollection.version3.1.obj"); // resetFull(); // writeExternalFormToDisk( // (java.io.Serializable) map, // "D:/dev/collections/data/test/SingletonMap.fullCollection.version3.1.obj"); // } } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/map/TestStaticBucketMap.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/map/TestStaticBucketMap.ja0000644000175000017500000000647510777673423032360 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.map; import java.util.Map; import junit.framework.Test; import org.apache.commons.collections.BulkTest; /** * Unit tests. * {@link StaticBucketMap}. * * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Michael A. Smith */ 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 }; } // Bugzilla 37567 public void test_get_nullMatchesIncorrectly() { StaticBucketMap map = new StaticBucketMap(17); map.put(null, "A"); assertEquals("A", map.get(null)); // loop so we find a string that is in the same bucket as the null for (int i = 'A'; i <= 'Z'; i++) { String str = String.valueOf((char) i); assertEquals("String: " + str, null, map.get(str)); } } public void test_containsKey_nullMatchesIncorrectly() { StaticBucketMap map = new StaticBucketMap(17); map.put(null, "A"); assertEquals(true, map.containsKey(null)); // loop so we find a string that is in the same bucket as the null for (int i = 'A'; i <= 'Z'; i++) { String str = String.valueOf((char) i); assertEquals("String: " + str, false, map.containsKey(str)); } } public void test_containsValue_nullMatchesIncorrectly() { StaticBucketMap map = new StaticBucketMap(17); map.put("A", null); assertEquals(true, map.containsValue(null)); // loop so we find a string that is in the same bucket as the null for (int i = 'A'; i <= 'Z'; i++) { String str = String.valueOf((char) i); assertEquals("String: " + str, false, map.containsValue(str)); } } } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/map/TestTransformedMap.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/map/TestTransformedMap.jav0000644000175000017500000001364010777673423032435 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.map; import java.util.HashMap; import java.util.Map; import java.util.Set; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.collections.TransformerUtils; import org.apache.commons.collections.collection.TestTransformedCollection; /** * Extension of {@link TestMap} for exercising the {@link TransformedMap} * implementation. * * @since Commons Collections 3.0 * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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 void testFactory_Decorate() { Map base = new HashMap(); base.put("A", "1"); base.put("B", "2"); base.put("C", "3"); Map trans = TransformedMap.decorate(base, null, TestTransformedCollection.STRING_TO_INTEGER_TRANSFORMER); assertEquals(3, trans.size()); assertEquals("1", trans.get("A")); assertEquals("2", trans.get("B")); assertEquals("3", trans.get("C")); trans.put("D", "4"); assertEquals(new Integer(4), trans.get("D")); } public void testFactory_decorateTransform() { Map base = new HashMap(); base.put("A", "1"); base.put("B", "2"); base.put("C", "3"); Map trans = TransformedMap.decorateTransform(base, null, TestTransformedCollection.STRING_TO_INTEGER_TRANSFORMER); assertEquals(3, trans.size()); assertEquals(new Integer(1), trans.get("A")); assertEquals(new Integer(2), trans.get("B")); assertEquals(new Integer(3), trans.get("C")); trans.put("D", "4"); assertEquals(new Integer(4), trans.get("D")); } //----------------------------------------------------------------------- public String getCompatibilityVersion() { return "3.1"; } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk( // (java.io.Serializable) map, // "D:/dev/collections/data/test/TransformedMap.emptyCollection.version3.1.obj"); // resetFull(); // writeExternalFormToDisk( // (java.io.Serializable) map, // "D:/dev/collections/data/test/TransformedMap.fullCollection.version3.1.obj"); // } } ././@LongLink0000000000000000000000000000015400000000000011565 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/map/TestTransformedSortedMap.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/map/TestTransformedSortedM0000644000175000017500000001454610777673423032524 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.map; import java.util.Map; import java.util.Set; import java.util.SortedMap; import java.util.TreeMap; import junit.framework.Test; import org.apache.commons.collections.BulkTest; import org.apache.commons.collections.TransformerUtils; import org.apache.commons.collections.collection.TestTransformedCollection; /** * Extension of {@link AbstractTestSortedMap} for exercising the {@link TransformedSortedMap} * implementation. * * @since Commons Collections 3.0 * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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 void testFactory_Decorate() { SortedMap base = new TreeMap(); base.put("A", "1"); base.put("B", "2"); base.put("C", "3"); SortedMap trans = TransformedSortedMap.decorate(base, null, TestTransformedCollection.STRING_TO_INTEGER_TRANSFORMER); assertEquals(3, trans.size()); assertEquals("1", trans.get("A")); assertEquals("2", trans.get("B")); assertEquals("3", trans.get("C")); trans.put("D", "4"); assertEquals(new Integer(4), trans.get("D")); } public void testFactory_decorateTransform() { SortedMap base = new TreeMap(); base.put("A", "1"); base.put("B", "2"); base.put("C", "3"); SortedMap trans = TransformedSortedMap.decorateTransform(base, null, TestTransformedCollection.STRING_TO_INTEGER_TRANSFORMER); assertEquals(3, trans.size()); assertEquals(new Integer(1), trans.get("A")); assertEquals(new Integer(2), trans.get("B")); assertEquals(new Integer(3), trans.get("C")); trans.put("D", "4"); assertEquals(new Integer(4), trans.get("D")); } //----------------------------------------------------------------------- public String getCompatibilityVersion() { return "3.1"; } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk( // (java.io.Serializable) map, // "D:/dev/collections/data/test/TransformedSortedMap.emptyCollection.version3.1.obj"); // resetFull(); // writeExternalFormToDisk( // (java.io.Serializable) map, // "D:/dev/collections/data/test/TransformedSortedMap.fullCollection.version3.1.obj"); // } } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/map/TestUnmodifiableMap.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/map/TestUnmodifiableMap.ja0000644000175000017500000000653110777673423032362 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.map; import java.util.HashMap; import java.util.Map; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.collections.Unmodifiable; /** * Extension of {@link AbstractTestMap} for exercising the * {@link UnmodifiableMap} implementation. * * @since Commons Collections 3.0 * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Phil Steitz */ 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/collections/data/test/UnmodifiableMap.emptyCollection.version3.1.obj"); // resetFull(); // writeExternalFormToDisk( // (java.io.Serializable) map, // "D:/dev/collections/data/test/UnmodifiableMap.fullCollection.version3.1.obj"); // } }././@LongLink0000000000000000000000000000015600000000000011567 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/map/TestUnmodifiableOrderedMap.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/map/TestUnmodifiableOrdere0000644000175000017500000000705510777673423032476 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.map; import java.util.HashMap; import java.util.Map; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.collections.OrderedMap; import org.apache.commons.collections.Unmodifiable; /** * Extension of {@link AbstractTestOrderedMap} for exercising the * {@link UnmodifiableOrderedMap} implementation. * * @since Commons Collections 3.0 * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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/collections/data/test/UnmodifiableOrderedMap.emptyCollection.version3.1.obj"); // resetFull(); // writeExternalFormToDisk( // (java.io.Serializable) map, // "D:/dev/collections/data/test/UnmodifiableOrderedMap.fullCollection.version3.1.obj"); // } }././@LongLink0000000000000000000000000000015500000000000011566 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/map/TestUnmodifiableSortedMap.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/map/TestUnmodifiableSorted0000644000175000017500000000672610777673423032522 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.map; import java.util.Map; import java.util.SortedMap; import java.util.TreeMap; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.collections.Unmodifiable; /** * Extension of {@link AbstractTestSortedMap} for exercising the * {@link UnmodifiableSortedMap} implementation. * * @since Commons Collections 3.0 * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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/collections/data/test/UnmodifiableSortedMap.emptyCollection.version3.1.obj"); // resetFull(); // writeExternalFormToDisk( // (java.io.Serializable) map, // "D:/dev/collections/data/test/UnmodifiableSortedMap.fullCollection.version3.1.obj"); // } }libcommons-collections3-java.orig/src/test/org/apache/commons/collections/set/0000755000175000017500000000000011010124151026125 5ustar godgodlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/set/AbstractTestSet.java0000644000175000017500000001430210777673430032103 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.set; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import org.apache.commons.collections.collection.AbstractTestCollection; /** * 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. * * @since Commons Collections 3.0 * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Paul Jack */ 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()); } } ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/set/AbstractTestSortedSet.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/set/AbstractTestSortedSet.0000644000175000017500000002712210777673430032426 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.set; import java.util.Collection; import java.util.Iterator; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import org.apache.commons.collections.BulkTest; /** * 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. * * @since Commons Collections 3.0 * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne * @author Dieter Wimberger */ 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; } } libcommons-collections3-java.orig/src/test/org/apache/commons/collections/set/TestAll.java0000644000175000017500000000455210777673430030402 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.set; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * Entry point for tests. * * @since Commons Collections 3.0 * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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; } } libcommons-collections3-java.orig/src/test/org/apache/commons/collections/set/TestCompositeSet.java0000644000175000017500000001353210777673430032306 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.set; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.collections.collection.CompositeCollection; import java.util.Set; import java.util.HashSet; import java.util.Collection; /** * Extension of {@link AbstractTestSet} for exercising the * {@link CompositeSet} implementation. * * @since Commons Collections 3.0 * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Brian McCallister * @author Phil Steitz */ 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 } } } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/set/TestListOrderedSet.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/set/TestListOrderedSet.jav0000644000175000017500000001673710777673430032435 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.set; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import junit.framework.Test; import junit.framework.TestSuite; /** * Extension of {@link TestSet} for exercising the {@link ListOrderedSet} * implementation. * * @since Commons Collections 3.0 * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Henning P. Schmiedehausen * @author Stephen Colebourne */ 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(); 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 testListAddReplacing() { ListOrderedSet set = (ListOrderedSet) makeEmptySet(); A a = new A(); B b = new B(); set.add(a); assertEquals(1, set.size()); set.add(b); // will match but not replace A as equal assertEquals(1, set.size()); assertSame(a, set.getSet().iterator().next()); assertSame(a, set.iterator().next()); assertSame(a, set.get(0)); assertSame(a, set.asList().get(0)); } static class A { public boolean equals(Object obj) { return (obj instanceof A || obj instanceof B); } public int hashCode() { return 1; } } static class B { public boolean equals(Object obj) { return (obj instanceof A || obj instanceof B); } public int hashCode() { return 1; } } 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/collections/data/test/ListOrderedSet.emptyCollection.version3.1.obj"); // resetFull(); // writeExternalFormToDisk((java.io.Serializable) collection, "D:/dev/collections/data/test/ListOrderedSet.fullCollection.version3.1.obj"); // } } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/set/TestListOrderedSet2.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/set/TestListOrderedSet2.ja0000644000175000017500000001351610777673430032321 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.set; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Set; import junit.framework.Test; import junit.framework.TestSuite; /** * Extension of {@link TestSet} for exercising the {@link ListOrderedSet} * implementation. * * @since Commons Collections 3.1 * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Henning P. Schmiedehausen * @author Stephen Colebourne */ 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/collections/data/test/ListOrderedSet.emptyCollection.version3.1.obj"); // resetFull(); // writeExternalFormToDisk((java.io.Serializable) collection, "D:/dev/collections/data/test/ListOrderedSet.fullCollection.version3.1.obj"); // } } libcommons-collections3-java.orig/src/test/org/apache/commons/collections/set/TestMapBackedSet.java0000644000175000017500000000424710777673430032156 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.set; import java.util.Set; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.collections.map.HashedMap; /** * JUnit test. * * @since Commons Collections 3.1 * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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/collections/data/test/MapBackedSet.emptyCollection.version3.1.obj"); // resetFull(); // writeExternalFormToDisk((java.io.Serializable) collection, "D:/dev/collections/data/test/MapBackedSet.fullCollection.version3.1.obj"); // } } ././@LongLink0000000000000000000000000000014500000000000011565 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/set/TestMapBackedSet2.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/set/TestMapBackedSet2.java0000644000175000017500000000605610777673430032240 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.set; import java.util.Iterator; import java.util.Set; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.collections.map.LinkedMap; /** * JUnit test. * * @since Commons Collections 3.1 * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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() { } } ././@LongLink0000000000000000000000000000014500000000000011565 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/set/TestPredicatedSet.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/set/TestPredicatedSet.java0000644000175000017500000001102410777673430032402 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.set; import java.util.HashSet; import java.util.Set; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.collections.Predicate; import org.apache.commons.collections.PredicateUtils; /** * Extension of {@link TestSet} for exercising the * {@link PredicatedSet} implementation. * * @since Commons Collections 3.0 * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Phil Steitz */ 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/collections/data/test/PredicatedSet.emptyCollection.version3.1.obj"); // resetFull(); // writeExternalFormToDisk((java.io.Serializable) collection, "D:/dev/collections/data/test/PredicatedSet.fullCollection.version3.1.obj"); // } }././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/set/TestPredicatedSortedSet.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/set/TestPredicatedSortedSe0000644000175000017500000001201010777673430032453 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.set; import java.util.Arrays; import java.util.Comparator; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import junit.framework.Test; import org.apache.commons.collections.BulkTest; import org.apache.commons.collections.Predicate; import org.apache.commons.collections.PredicateUtils; import org.apache.commons.collections.map.TestPredicatedSortedMap; /** * Extension of {@link AbstractTestSortedSet} for exercising the * {@link PredicatedSortedSet} implementation. * * @since Commons Collections 3.0 * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Phil Steitz */ 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/collections/data/test/PredicatedSortedSet.emptyCollection.version3.1.obj"); // resetFull(); // writeExternalFormToDisk((java.io.Serializable) collection, "D:/dev/collections/data/test/PredicatedSortedSet.fullCollection.version3.1.obj"); // } } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/set/TestSynchronizedSet.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/set/TestSynchronizedSet.ja0000644000175000017500000000455210777673430032476 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.set; import java.util.HashSet; import java.util.Set; import junit.framework.Test; import org.apache.commons.collections.BulkTest; /** * Extension of {@link AbstractTestSet} for exercising the * {@link SynchronizedSet} implementation. * * @since Commons Collections 3.1 * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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/collections/data/test/SynchronizedSet.emptyCollection.version3.1.obj"); // resetFull(); // writeExternalFormToDisk((java.io.Serializable) collection, "D:/dev/collections/data/test/SynchronizedSet.fullCollection.version3.1.obj"); // } } ././@LongLink0000000000000000000000000000015500000000000011566 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/set/TestSynchronizedSortedSet.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/set/TestSynchronizedSorted0000644000175000017500000000464010777673430032610 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.set; import java.util.Set; import java.util.TreeSet; import junit.framework.Test; import org.apache.commons.collections.BulkTest; /** * Extension of {@link AbstractTestSet} for exercising the * {@link SynchronizedSortedSet} implementation. * * @since Commons Collections 3.1 * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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/collections/data/test/SynchronizedSortedSet.emptyCollection.version3.1.obj"); // resetFull(); // writeExternalFormToDisk((java.io.Serializable) collection, "D:/dev/collections/data/test/SynchronizedSortedSet.fullCollection.version3.1.obj"); // } } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/set/TestTransformedSet.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/set/TestTransformedSet.jav0000644000175000017500000000707210777673430032471 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.set; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.Set; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.collections.collection.TestTransformedCollection; /** * Extension of {@link TestSet} for exercising the {@link TransformedSet} * implementation. * * @since Commons Collections 3.0 * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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/collections/data/test/TransformedSet.emptyCollection.version3.1.obj"); // resetFull(); // writeExternalFormToDisk((java.io.Serializable) collection, "D:/dev/collections/data/test/TransformedSet.fullCollection.version3.1.obj"); // } } ././@LongLink0000000000000000000000000000015400000000000011565 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/set/TestTransformedSortedSet.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/set/TestTransformedSortedS0000644000175000017500000000710710777673430032541 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.set; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import junit.framework.Test; import org.apache.commons.collections.BulkTest; import org.apache.commons.collections.collection.TestTransformedCollection; /** * Extension of {@link TestSortedSet} for exercising the {@link TransformedSortedSet} * implementation. * * @since Commons Collections 3.0 * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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/collections/data/test/TransformedSortedSet.emptyCollection.version3.1.obj"); // resetFull(); // writeExternalFormToDisk((java.io.Serializable) collection, "D:/dev/collections/data/test/TransformedSortedSet.fullCollection.version3.1.obj"); // } } libcommons-collections3-java.orig/src/test/org/apache/commons/collections/set/TestTypedSet.java0000644000175000017500000000404010777673430031423 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.set; import java.util.HashSet; import java.util.Set; import junit.framework.Test; import org.apache.commons.collections.BulkTest; /** * Extension of {@link AbstractTestSet} for exercising the * {@link TypedSet} implementation. * * @since Commons Collections 3.1 * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Phil Steitz */ 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 rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/set/TestTypedSortedSet.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/set/TestTypedSortedSet.jav0000644000175000017500000000720210777673430032446 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.set; import java.util.Arrays; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import junit.framework.Test; import org.apache.commons.collections.BulkTest; /** * Extension of {@link AbstractTestSortedSet} for exercising the * {@link TypedSortedSet} implementation. * * @since Commons Collections 3.0 * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Phil Steitz */ 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 } } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/set/TestUnmodifiableSet.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/set/TestUnmodifiableSet.ja0000644000175000017500000000531410777673430032412 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.set; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import junit.framework.Test; import org.apache.commons.collections.BulkTest; /** * Extension of {@link AbstractTestSet} for exercising the * {@link UnmodifiableSet} implementation. * * @since Commons Collections 3.0 * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Phil Steitz */ 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/collections/data/test/UnmodifiableSet.emptyCollection.version3.1.obj"); // resetFull(); // writeExternalFormToDisk((java.io.Serializable) collection, "D:/dev/collections/data/test/UnmodifiableSet.fullCollection.version3.1.obj"); // } } ././@LongLink0000000000000000000000000000015500000000000011566 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/set/TestUnmodifiableSortedSet.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/set/TestUnmodifiableSorted0000644000175000017500000001201210777673430032517 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.set; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.Set; import java.util.TreeSet; import junit.framework.Test; import org.apache.commons.collections.BulkTest; /** * Extension of {@link AbstractTestSortedSet} for exercising the * {@link UnmodifiableSortedSet} implementation. * * @since Commons Collections 3.0 * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Phil Steitz */ 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/collections/data/test/UnmodifiableSortedSet.emptyCollection.version3.1.obj"); // resetFull(); // writeExternalFormToDisk((java.io.Serializable) collection, "D:/dev/collections/data/test/UnmodifiableSortedSet.fullCollection.version3.1.obj"); // } } libcommons-collections3-java.orig/src/test/org/apache/commons/collections/AbstractTestObject.java0000644000175000017500000003022510777673435031772 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.io.Serializable; /** * 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. * * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Rodney Waldhoff * @author Stephen Colebourne * @author Anonymous */ 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 collections 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 * @exception 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 * @exception 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 * @exception IOException * @exception 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 * @exception IOException * @exception 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.collections: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); } } libcommons-collections3-java.orig/src/test/org/apache/commons/collections/BulkTest.java0000644000175000017500000003702110777673435027776 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; 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; import junit.framework.TestCase; import junit.framework.TestSuite; /** * 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 Paul Jack * @version $Id: BulkTest.java 646780 2008-04-10 12:48:07Z niallp $ */ 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, (Object[]) 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 Object[] {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; } } libcommons-collections3-java.orig/src/test/org/apache/commons/collections/LocalTestNode.java0000644000175000017500000000577310777673435030752 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; /** * Class LocalTestNode, a helper class for TestDoubleOrderedMap * * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Marc Johnson (marcj at users dot sourceforge dot net) */ 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(); } } libcommons-collections3-java.orig/src/test/org/apache/commons/collections/MapPerformance.java0000644000175000017500000001402410777673435031136 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.TreeMap; import org.apache.commons.collections.map.Flat3Map; /** * TestMapPerformance is designed to perform basic Map performance tests. * * @author Stephen Colebourne */ public class MapPerformance { /** The total number of runs for each test */ private static final int RUNS = 20000000; /** * Main method */ public static void main(String[] args) { testAll(); } private static void testAll() { Map dummyMap = new DummyMap(); Map hashMap = new HashMap(); // hashMap.put("Alpha", "A"); // hashMap.put("Beta", "B"); // hashMap.put("Gamma", "C"); // hashMap.put("Delta", "D"); Map flatMap = new Flat3Map(hashMap); System.out.println(flatMap); Map unmodHashMap = Collections.unmodifiableMap(new HashMap(hashMap)); Map fastHashMap = new FastHashMap(hashMap); Map treeMap = new TreeMap(hashMap); Map seqMap = new SequencedHashMap(hashMap); // Map linkedMap = new LinkedHashMap(hashMap); // Map syncMap = Collections.unmodifiableMap(new HashMap(hashMap)); // Map bucketMap = new StaticBucketMap(); // bucketMap.putAll(hashMap); // Map doubleMap = new DoubleOrderedMap(hashMap); // dummy is required as the VM seems to hotspot the first call to the // test method with the given type test(dummyMap, " Dummy "); test(dummyMap, " Dummy "); test(dummyMap, " Dummy "); test(flatMap, " Flat3 "); test(hashMap, " HashMap "); test(flatMap, " Flat3 "); test(flatMap, " Flat3 "); test(flatMap, " Flat3 "); test(hashMap, " HashMap "); test(hashMap, " HashMap "); test(hashMap, " HashMap "); // test(treeMap, " TreeMap "); // test(treeMap, " TreeMap "); // test(treeMap, " TreeMap "); // test(unmodHashMap, "Unmod(HashMap) "); // test(unmodHashMap, "Unmod(HashMap) "); // test(unmodHashMap, "Unmod(HashMap) "); // // test(syncMap, " Sync(HashMap) "); // test(syncMap, " Sync(HashMap) "); // test(syncMap, " Sync(HashMap) "); // // test(fastHashMap, " FastHashMap "); // test(fastHashMap, " FastHashMap "); // test(fastHashMap, " FastHashMap "); // // test(seqMap, " SeqHashMap "); // test(seqMap, " SeqHashMap "); // test(seqMap, " SeqHashMap "); // // test(linkedMap, " LinkedHashMap "); // test(linkedMap, " LinkedHashMap "); // test(linkedMap, " LinkedHashMap "); // // test(bucketMap, " BucketMap "); // test(bucketMap, " BucketMap "); // test(bucketMap, " BucketMap "); // // test(doubleMap, " DoubleMap "); // test(doubleMap, " DoubleMap "); // test(doubleMap, " DoubleMap "); } private static void test(Map map, String name) { long start = 0, end = 0; int total = 0; start = System.currentTimeMillis(); for (int i = RUNS; i > 0; i--) { // if (map.get("Alpha") != null) total++; // if (map.get("Beta") != null) total++; // if (map.get("Gamma") != null) total++; map.put("Alpha", "A"); map.put("Beta", "B"); map.put("Beta", "C"); map.put("Gamma", "D"); // map.remove("Gamma"); // map.remove("Beta"); // map.remove("Alpha"); map.put("Delta", "E"); map.clear(); } end = System.currentTimeMillis(); System.out.println(name + (end - start)); } // ---------------------------------------------------------------------- private static class DummyMap implements Map { public void clear() { } public boolean containsKey(Object key) { return false; } public boolean containsValue(Object value) { return false; } public Set entrySet() { return null; } public Object get(Object key) { return null; } public boolean isEmpty() { return false; } public Set keySet() { return null; } public Object put(Object key, Object value) { return null; } public void putAll(Map t) { } public Object remove(Object key) { return null; } public int size() { return 0; } public Collection values() { return null; } } } libcommons-collections3-java.orig/src/test/org/apache/commons/collections/overview.html0000644000175000017500000000351610777673435030134 0ustar godgod

              The Collections Test Framework is an extension to JUnit to enable quick and easy testing of collections.

              Apache 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. libcommons-collections3-java.orig/src/test/org/apache/commons/collections/TestAll.java0000644000175000017500000000637210777673435027616 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * Entry point for all Collections package tests. * * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Rodney Waldhoff * @author Stephen Colebourne */ 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(TestBoundedFifoBuffer.suite()); suite.addTest(TestBoundedFifoBuffer2.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); } } libcommons-collections3-java.orig/src/test/org/apache/commons/collections/TestAllPackages.java0000644000175000017500000000463710777673435031257 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * Entry point for all Collections project tests. * * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ public class TestAllPackages extends TestCase { public TestAllPackages(String testName) { super(testName); } public static Test suite() { TestSuite suite = new TestSuite(); suite.addTest(org.apache.commons.collections.TestAll.suite()); suite.addTest(org.apache.commons.collections.bag.TestAll.suite()); suite.addTest(org.apache.commons.collections.bidimap.TestAll.suite()); suite.addTest(org.apache.commons.collections.buffer.TestAll.suite()); suite.addTest(org.apache.commons.collections.collection.TestAll.suite()); suite.addTest(org.apache.commons.collections.comparators.TestAll.suite()); suite.addTest(org.apache.commons.collections.iterators.TestAll.suite()); suite.addTest(org.apache.commons.collections.keyvalue.TestAll.suite()); suite.addTest(org.apache.commons.collections.list.TestAll.suite()); suite.addTest(org.apache.commons.collections.map.TestAll.suite()); suite.addTest(org.apache.commons.collections.set.TestAll.suite()); return suite; } public static void main(String args[]) { String[] testCaseName = { TestAllPackages.class.getName() }; junit.textui.TestRunner.main(testCaseName); } } libcommons-collections3-java.orig/src/test/org/apache/commons/collections/TestArrayList.java0000644000175000017500000000466210777673435031020 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; import java.util.ArrayList; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.collections.list.AbstractTestList; /** * Abstract test class for ArrayList. * * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Jason van Zyl */ 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"); } } libcommons-collections3-java.orig/src/test/org/apache/commons/collections/TestArrayStack.java0000644000175000017500000000760310777673435031150 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; import java.util.EmptyStackException; import java.util.List; import junit.framework.Test; /** * Tests ArrayStack. * * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Craig McClanahan */ 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); } } libcommons-collections3-java.orig/src/test/org/apache/commons/collections/TestBagUtils.java0000644000175000017500000002054010777673435030611 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; import junit.framework.Test; import org.apache.commons.collections.bag.HashBag; import org.apache.commons.collections.bag.PredicatedBag; import org.apache.commons.collections.bag.PredicatedSortedBag; import org.apache.commons.collections.bag.SynchronizedBag; import org.apache.commons.collections.bag.SynchronizedSortedBag; import org.apache.commons.collections.bag.TransformedBag; import org.apache.commons.collections.bag.TransformedSortedBag; import org.apache.commons.collections.bag.TreeBag; import org.apache.commons.collections.bag.UnmodifiableBag; import org.apache.commons.collections.bag.UnmodifiableSortedBag; /** * Tests for BagUtils factory methods. * * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Phil Steitz */ 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 } } } libcommons-collections3-java.orig/src/test/org/apache/commons/collections/TestBeanMap.java0000644000175000017500000002655010777673435030411 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; import java.io.Serializable; import java.lang.reflect.Method; import java.util.Map; import junit.framework.Test; import junit.textui.TestRunner; import org.apache.commons.collections.map.AbstractTestMap; /** * Test cases for BeanMap * * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Morgan Delagrange * @author Stephen Colebourne */ 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", (Class[]) 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")); } } libcommons-collections3-java.orig/src/test/org/apache/commons/collections/TestBinaryHeap.java0000644000175000017500000002705510777673435031131 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Comparator; import java.util.NoSuchElementException; import java.util.Random; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.collections.collection.AbstractTestCollection; import org.apache.commons.collections.comparators.ComparableComparator; import org.apache.commons.collections.comparators.ReverseComparator; /** * Tests the BinaryHeap. * * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Michael A. Smith */ public class TestBinaryHeap extends AbstractTestCollection { public static Test suite() { return new TestSuite(TestBinaryHeap.class); } public TestBinaryHeap(String testName) { super(testName); } //----------------------------------------------------------------------- public void verify() { super.verify(); BinaryHeap heap = (BinaryHeap) collection; Comparator c = heap.m_comparator; if (c == null) c = ComparatorUtils.naturalComparator(); if (!heap.m_isMinHeap) c = ComparatorUtils.reversedComparator(c); Object[] tree = heap.m_elements; for (int i = 1; i <= heap.m_size; i++) { Object parent = tree[i]; if (i * 2 <= heap.m_size) { assertTrue("Parent is less than or equal to its left child", c.compare(parent, tree[i * 2]) <= 0); } if (i * 2 + 1 < heap.m_size) { assertTrue("Parent is less than or equal to its right child", c.compare(parent, tree[i * 2 + 1]) <= 0); } } } //----------------------------------------------------------------------- /** * Overridden because UnboundedFifoBuffer 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 BinaryHeap(); } //----------------------------------------------------------------------- public Object[] getFullElements() { return getFullNonNullStringElements(); } public Object[] getOtherElements() { return getOtherNonNullStringElements(); } //----------------------------------------------------------------------- public void testBasicOps() { BinaryHeap heap = new BinaryHeap(); assertTrue("heap should be empty after create", heap.isEmpty()); try { heap.peek(); fail("NoSuchElementException should be thrown if peek is called before any elements are inserted"); } catch (NoSuchElementException e) { // expected } try { heap.pop(); fail("NoSuchElementException should be thrown if pop is called before any elements are inserted"); } catch (NoSuchElementException e) { // expected } heap.insert("a"); heap.insert("c"); heap.insert("e"); heap.insert("b"); heap.insert("d"); heap.insert("n"); heap.insert("m"); heap.insert("l"); heap.insert("k"); heap.insert("j"); heap.insert("i"); heap.insert("h"); heap.insert("g"); heap.insert("f"); assertTrue("heap should not be empty after inserts", !heap.isEmpty()); for (int i = 0; i < 14; i++) { assertEquals( "peek using default constructor should return minimum value in the binary heap", String.valueOf((char) ('a' + i)), heap.peek()); assertEquals( "pop using default constructor should return minimum value in the binary heap", String.valueOf((char) ('a' + i)), heap.pop()); if (i + 1 < 14) { assertTrue("heap should not be empty before all elements are popped", !heap.isEmpty()); } else { assertTrue("heap should be empty after all elements are popped", heap.isEmpty()); } } try { heap.peek(); fail("NoSuchElementException should be thrown if peek is called after all elements are popped"); } catch (NoSuchElementException e) { // expected } try { heap.pop(); fail("NoSuchElementException should be thrown if pop is called after all elements are popped"); } catch (NoSuchElementException e) { // expected } } public void testBasicComparatorOps() { BinaryHeap heap = new BinaryHeap(new ReverseComparator(new ComparableComparator())); assertTrue("heap should be empty after create", heap.isEmpty()); try { heap.peek(); fail("NoSuchElementException should be thrown if peek is called before any elements are inserted"); } catch (NoSuchElementException e) { // expected } try { heap.pop(); fail("NoSuchElementException should be thrown if pop is called before any elements are inserted"); } catch (NoSuchElementException e) { // expected } heap.insert("a"); heap.insert("c"); heap.insert("e"); heap.insert("b"); heap.insert("d"); heap.insert("n"); heap.insert("m"); heap.insert("l"); heap.insert("k"); heap.insert("j"); heap.insert("i"); heap.insert("h"); heap.insert("g"); heap.insert("f"); assertTrue("heap should not be empty after inserts", !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( "peek using default constructor should return minimum value in the binary heap", String.valueOf((char) ('n' - i)), heap.peek()); assertEquals( "pop using default constructor should return minimum value in the binary heap", String.valueOf((char) ('n' - i)), heap.pop()); if (i + 1 < 14) { assertTrue("heap should not be empty before all elements are popped", !heap.isEmpty()); } else { assertTrue("heap should be empty after all elements are popped", heap.isEmpty()); } } try { heap.peek(); fail("NoSuchElementException should be thrown if peek is called after all elements are popped"); } catch (NoSuchElementException e) { // expected } try { heap.pop(); fail("NoSuchElementException should be thrown if pop is called after all elements are popped"); } catch (NoSuchElementException e) { // expected } } /** * Illustrates bad internal heap state reported in Bugzilla PR #235818. */ public void testAddRemove() { resetEmpty(); BinaryHeap heap = (BinaryHeap) 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(); BinaryHeap h = null; for(int i=0; i < iterations; i++) { if (i < iterations / 2) { h = new BinaryHeap(true); } else { h = new BinaryHeap(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(BinaryHeap h) { Integer lastNum = null; Integer num = null; boolean fail = false; while (!h.isEmpty()) { num = (Integer) h.pop(); if (h.m_isMinHeap) { 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(BinaryHeap 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.m_elements.length && h.m_elements[i] != null) buffer.append(h.m_elements[i] + " "); count++; } buffer.append('\n'); } return buffer.toString(); } } ././@LongLink0000000000000000000000000000014500000000000011565 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/TestBoundedFifoBuffer.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/TestBoundedFifoBuffer.java0000644000175000017500000001166310777673435032423 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import junit.framework.Test; import org.apache.commons.collections.collection.AbstractTestCollection; /** * Test cases for BoundedFifoBuffer. * * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Paul Jack */ 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(); } } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/TestBoundedFifoBuffer2.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/TestBoundedFifoBuffer2.jav0000644000175000017500000000736310777673435032346 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; import java.util.Arrays; import java.util.Collection; import junit.framework.Test; /** * Runs tests against a full BoundedFifoBuffer, since many of the algorithms * differ depending on whether the fifo is full or not. * * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Unknown */ 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()); } } libcommons-collections3-java.orig/src/test/org/apache/commons/collections/TestBufferUtils.java0000644000175000017500000000441610777673435031335 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; import junit.framework.Test; import org.apache.commons.collections.buffer.PredicatedBuffer; /** * Tests for BufferUtils. * * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Unknown */ 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 } } } libcommons-collections3-java.orig/src/test/org/apache/commons/collections/TestClosureUtils.java0000644000175000017500000003457610777673435031552 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map; import junit.framework.Test; import junit.framework.TestSuite; import junit.textui.TestRunner; import org.apache.commons.collections.functors.NOPClosure; /** * Tests the org.apache.commons.collections.ClosureUtils class. * * @since Commons Collections 3.0 * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ public class TestClosureUtils extends junit.framework.TestCase { private static final Object cString = "Hello"; /** * 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) {} } // ifClosure //------------------------------------------------------------------ public void testIfClosure() { MockClosure a = new MockClosure(); MockClosure b = null; ClosureUtils.ifClosure(PredicateUtils.truePredicate(), a).execute(null); assertEquals(1, a.count); a = new MockClosure(); ClosureUtils.ifClosure(PredicateUtils.falsePredicate(), a).execute(null); assertEquals(0, a.count); a = new 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); } // switchClosure //------------------------------------------------------------------ public void testSwitchClosure() { MockClosure a = new MockClosure(); 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)); } } libcommons-collections3-java.orig/src/test/org/apache/commons/collections/TestCollectionUtils.java0000644000175000017500000014571310777673435032225 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; import java.util.ArrayList; import java.util.Collection; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.SortedMap; import java.util.TreeMap; import java.util.Vector; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.apache.commons.collections.bag.HashBag; import org.apache.commons.collections.buffer.BoundedFifoBuffer; import org.apache.commons.collections.collection.AbstractTestCollection; import org.apache.commons.collections.collection.PredicatedCollection; import org.apache.commons.collections.collection.SynchronizedCollection; import org.apache.commons.collections.collection.TransformedCollection; import org.apache.commons.collections.collection.UnmodifiableCollection; /** * Tests for CollectionUtils. * * @author Rodney Waldhoff * @author Matthew Hawthorne * @author Stephen Colebourne * @author Phil Steitz * @author Steven Melzer * @author Neil O'Toole * @author Stephen Smith * * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ */ 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)); 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 en = vector.elements(); test = CollectionUtils.index(en,0); assertTrue(test.equals("zero")); en = vector.elements(); test = CollectionUtils.index(en,1); assertTrue(test.equals("one")); // Enumeration, non-existent entry -- "dead" enumerator returned test = CollectionUtils.index(en,3); assertTrue(test.equals(en) && !en.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 en = vector.elements(); assertEquals("zero",CollectionUtils.get(en,0)); en = vector.elements(); assertEquals("one",CollectionUtils.get(en,1)); // Enumerator, non-existent entry try { CollectionUtils.get(en,3); fail("Expecting IndexOutOfBoundsException."); } catch (IndexOutOfBoundsException e) { // expected } assertTrue(!en.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) {} } //----------------------------------------------------------------------- public void testSizeIsEmpty_List() { List list = new ArrayList(); assertEquals(true, CollectionUtils.sizeIsEmpty(list)); list.add("a"); assertEquals(false, CollectionUtils.sizeIsEmpty(list)); } public void testSizeIsEmpty_Map() { Map map = new HashMap(); assertEquals(true, CollectionUtils.sizeIsEmpty(map)); map.put("1", "a"); assertEquals(false, CollectionUtils.sizeIsEmpty(map)); } public void testSizeIsEmpty_Array() { Object[] objectArray = new Object[0]; assertEquals(true, CollectionUtils.sizeIsEmpty(objectArray)); String[] stringArray = new String[3]; assertEquals(false, CollectionUtils.sizeIsEmpty(stringArray)); stringArray[0] = "a"; stringArray[1] = "b"; stringArray[2] = "c"; assertEquals(false, CollectionUtils.sizeIsEmpty(stringArray)); } public void testSizeIsEmpty_PrimitiveArray() { int[] intArray = new int[0]; assertEquals(true, CollectionUtils.sizeIsEmpty(intArray)); double[] doubleArray = new double[3]; assertEquals(false, CollectionUtils.sizeIsEmpty(doubleArray)); doubleArray[0] = 0.0d; doubleArray[1] = 1.0d; doubleArray[2] = 2.5d; assertEquals(false, CollectionUtils.sizeIsEmpty(doubleArray)); } public void testSizeIsEmpty_Enumeration() { Vector list = new Vector(); assertEquals(true, CollectionUtils.sizeIsEmpty(list.elements())); list.add("a"); assertEquals(false, CollectionUtils.sizeIsEmpty(list.elements())); Enumeration en = list.elements(); en.nextElement(); assertEquals(true, CollectionUtils.sizeIsEmpty(en)); } public void testSizeIsEmpty_Iterator() { List list = new ArrayList(); assertEquals(true, CollectionUtils.sizeIsEmpty(list.iterator())); list.add("a"); assertEquals(false, CollectionUtils.sizeIsEmpty(list.iterator())); Iterator it = list.iterator(); it.next(); assertEquals(true, CollectionUtils.sizeIsEmpty(it)); } public void testSizeIsEmpty_Other() { try { CollectionUtils.sizeIsEmpty(null); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) {} try { CollectionUtils.sizeIsEmpty("not a list"); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testIsEmptyWithEmptyCollection() { Collection coll = new ArrayList(); assertEquals(true, CollectionUtils.isEmpty(coll)); } public void testIsEmptyWithNonEmptyCollection() { Collection coll = new ArrayList(); coll.add("item"); assertEquals(false, CollectionUtils.isEmpty(coll)); } public void testIsEmptyWithNull() { Collection coll = null; assertEquals(true, CollectionUtils.isEmpty(coll)); } public void testIsNotEmptyWithEmptyCollection() { Collection coll = new ArrayList(); assertEquals(false, CollectionUtils.isNotEmpty(coll)); } public void testIsNotEmptyWithNonEmptyCollection() { Collection coll = new ArrayList(); coll.add("item"); assertEquals(true, CollectionUtils.isNotEmpty(coll)); } public void testIsNotEmptyWithNull() { Collection coll = null; assertEquals(false, CollectionUtils.isNotEmpty(coll)); } //----------------------------------------------------------------------- private static Predicate EQUALS_TWO = new Predicate() { public boolean evaluate(Object 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")); 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 testAddIgnoreNull() { Set set = new HashSet(); set.add("1"); set.add("2"); set.add("3"); assertEquals(false, CollectionUtils.addIgnoreNull(set, null)); assertEquals(3, set.size()); assertEquals(false, CollectionUtils.addIgnoreNull(set, "1")); assertEquals(3, set.size()); assertEquals(true, CollectionUtils.addIgnoreNull(set, "4")); assertEquals(4, set.size()); assertEquals(true, set.contains("4")); } //----------------------------------------------------------------------- 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 collections... 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 testTransformedCollection_2() { List list = new ArrayList(); list.add("1"); list.add("2"); list.add("3"); Collection result = CollectionUtils.transformedCollection(list, TRANSFORM_TO_INTEGER); assertEquals(true, result.contains("1")); // untransformed assertEquals(true, result.contains("2")); // untransformed assertEquals(true, result.contains("3")); // untransformed } 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 } } } ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/TestCursorableLinkedList.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/TestCursorableLinkedList.j0000644000175000017500000010426010777673435032475 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import junit.framework.Test; import org.apache.commons.collections.list.AbstractTestList; /** * Test class. * * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Rodney Waldhoff * @author Simon Kitching */ public class TestCursorableLinkedList extends AbstractTestList { 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(); } 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(); ListIterator li = list.listIterator(); // test cursors remain valid when list modified by std ListIterator // 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()); boolean nosuch = false; try { c2.next(); } catch (java.util.NoSuchElementException nse) { nosuch = true; // expected } assertTrue(nosuch); boolean listIteratorInvalid = false; try { li.next(); } catch(java.util.ConcurrentModificationException cme) { listIteratorInvalid = true; // expected } assertTrue(listIteratorInvalid); c1.close(); // not necessary c2.close(); // not necessary } 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]); } } libcommons-collections3-java.orig/src/test/org/apache/commons/collections/TestDoubleOrderedMap.java0000644000175000017500000022625610777673435032270 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; import java.util.Collection; import java.util.ConcurrentModificationException; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; import junit.framework.Test; import org.apache.commons.collections.map.AbstractTestMap; /** * Class TestDoubleOrderedMap *

              * Test cases for DoubleOrderedMap. This class cannot * implement TestMap.SupportsPut, because it is a special * Map that does not support duplicate keys, duplicate * values, or null values. * * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Marc Johnson * @author Stephen Colebourne */ public class TestDoubleOrderedMap extends AbstractTestMap { /** * constructor * * @param name */ public TestDoubleOrderedMap(final String name) { super(name); } /** * create a suite of the tests in this class * * @return the test suite */ public static Test suite() { return BulkTest.makeSuite(TestDoubleOrderedMap.class); } /** * The default comparator in double ordered map does not allow null keys. **/ public boolean isAllowNullKey() { return false; } /** * The default comparator in double ordered map does not allow null keys, * and values are keys in this map. **/ public boolean isAllowNullValue() { return false; } /** * Double ordered map does not support duplicate values **/ public boolean isAllowDuplicateValues() { return false; } /** * Change the Map.put() test because it tries put with the same key * which is invalid in the modified double ordered map contract. (The * DoubleOrderedMap documentation states that an IllegalArgumentException * is thrown when a key is tried to be put into the map again. This * differs from the standard Map contract which would replace the value * for that key and return it. */ public boolean isPutChangeSupported() { return false; } /** * setValue() is not supported as it can change the map. */ public boolean isSetValueSupported() { return false; } public Map makeEmptyMap() { return new DoubleOrderedMap(); } protected Map makeMap() { return new DoubleOrderedMap(); } /** * test size() method */ public void testSize() { Map m = makeMap(); assertEquals(0, m.size()); LocalTestNode nodes[] = makeLocalNodes(); for (int k = 0; k < nodes.length; k++) { m.put(nodes[k].getKey(), nodes[k].getValue()); assertEquals(k + 1, m.size()); } int count = m.size(); for (int k = 0; k < nodes.length; k++) { m.remove(nodes[k].getKey()); --count; assertEquals(count, m.size()); // failed remove should not affect size m.remove(nodes[k].getKey()); assertEquals(count, m.size()); } } /** * test IsEmpty() method */ public void testIsEmpty() { Map m = makeMap(); assertTrue(m.isEmpty()); LocalTestNode nodes[] = makeLocalNodes(); for (int k = 0; k < nodes.length; k++) { m.put(nodes[k].getKey(), nodes[k].getValue()); assertTrue(!m.isEmpty()); } int count = m.size(); for (int k = 0; k < nodes.length; k++) { m.remove(nodes[k].getKey()); --count; if (count == 0) { assertTrue(m.isEmpty()); } else { assertTrue(!m.isEmpty()); } // failed remove should not affect emptiness m.remove(nodes[k].getKey()); if (count == 0) { assertTrue(m.isEmpty()); } else { assertTrue(!m.isEmpty()); } } } /** * test containsKey() method */ public void testContainsKey() { Map m = makeMap(); try { m.containsKey(new Object()); fail("should have caught ClassCastException"); } catch (ClassCastException ignored) {} try { m.containsKey(null); fail("should have caught NullPointerException"); } catch (NullPointerException ignored) {} assertTrue(!m.containsKey("foo")); LocalTestNode nodes[] = makeLocalNodes(); for (int k = 0; k < nodes.length; k++) { m.put(nodes[k].getKey(), nodes[k]); assertTrue(m.containsKey(nodes[k].getKey())); } assertTrue(!m.containsKey(new Integer(-1))); try { m.containsKey("foo"); fail("Should have caught ClassCastException"); } catch (ClassCastException ignored) {} for (int k = 0; k < nodes.length; k++) { m.remove(nodes[k].getKey()); assertTrue(!m.containsKey(nodes[k].getKey())); } } /** * test containsValue() method */ public void testContainsValue() { Map m = (DoubleOrderedMap) makeMap(); LocalTestNode nodes[] = makeLocalNodes(); for (int k = 0; k < nodes.length; k++) { m.put(nodes[k].getKey(), nodes[k]); assertTrue(m.containsValue(nodes[k])); } for (int k = 0; k < nodes.length; k++) { m.remove(nodes[k].getKey()); assertTrue(!m.containsValue(nodes[k])); } } /** * test get() method */ public void testGet() { Map m = makeMap(); try { m.get(new Object()); fail("should have caught ClassCastException"); } catch (ClassCastException ignored) {} try { m.get(null); fail("should have caught NullPointerException"); } catch (NullPointerException ignored) {} assertNull(m.get("foo")); LocalTestNode nodes[] = makeLocalNodes(); for (int k = 0; k < nodes.length; k++) { m.put(nodes[k].getKey(), nodes[k]); assertSame(m.get(nodes[k].getKey()), nodes[k]); } assertNull(m.get(new Integer(-1))); try { m.get("foo"); fail("Should have caught ClassCastException"); } catch (ClassCastException ignored) {} for (int k = 0; k < nodes.length; k++) { assertNotNull(m.get(nodes[k].getKey())); m.remove(nodes[k].getKey()); assertNull(m.get(nodes[k].getKey())); } } /** * test put() method */ public void testPut() { Map m = makeMap(); try { m.put(new Object(), "foo"); fail("should have caught ClassCastException"); } catch (ClassCastException ignored) {} try { m.put(null, "foo"); fail("should have caught NullPointerException"); } catch (NullPointerException ignored) {} try { m.put("foo", null); fail("should have caught NullPointerException"); } catch (NullPointerException ignored) {} try { m.put("foo", new Object()); fail("should have caught ClassCastException"); } catch (ClassCastException ignored) {} LocalTestNode[] nodes = makeLocalNodes(); for (int k = 0; k < nodes.length; k++) { assertNull(m.put(nodes[k].getKey(), nodes[k].getValue())); try { m.put(nodes[k].getKey(), "foo"); } catch (IllegalArgumentException ignored) {} } } /** * test remove() method */ public void testRemove() { DoubleOrderedMap m = (DoubleOrderedMap) makeMap(); LocalTestNode nodes[] = makeLocalNodes(); for (int k = 0; k < nodes.length; k++) { m.put(nodes[k].getKey(), nodes[k]); } try { m.remove(null); fail("should have caught NullPointerException"); } catch (NullPointerException ignored) {} try { m.remove(new Object()); fail("should have caught ClassCastException"); } catch (ClassCastException ignored) {} assertNull(m.remove(new Integer(-1))); try { m.remove("foo"); fail("should have caught ClassCastException"); } catch (ClassCastException ignored) {} for (int k = 0; k < nodes.length; k += 2) { Comparable key = nodes[k].getKey(); assertNotNull(m.get(key)); assertSame(nodes[k], m.remove(key)); assertNull(m.remove(key)); assertNull(m.get(key)); } for (int k = 1; k < nodes.length; k += 2) { Comparable key = nodes[k].getKey(); assertNotNull(m.get(key)); assertSame(nodes[k], m.remove(key)); assertNull(m.remove(key)); assertNull(m.get(key)); } assertTrue(m.isEmpty()); } /** * Method testPutAll */ public void testPutAll() { Map m = (DoubleOrderedMap) makeMap(); LocalTestNode nodes[] = makeLocalNodes(); for (int k = 0; k < nodes.length; k++) { m.put(nodes[k].getKey(), nodes[k]); } Map m1 = new HashMap(); m1.put(null, "foo"); try { m.putAll(m1); fail("Should have caught NullPointerException"); } catch (NullPointerException ignored) {} m1 = new HashMap(); m1.put(new Object(), "bar"); try { m.putAll(m1); fail("Should have caught ClassCastException"); } catch (ClassCastException ignored) {} m1 = new HashMap(); m1.put("fubar", null); try { m.putAll(m1); fail("Should have caught NullPointerException"); } catch (NullPointerException ignored) {} m1 = new HashMap(); m1.put("fubar", new Object()); try { m.putAll(m1); fail("Should have caught ClassCastException"); } catch (ClassCastException ignored) {} assertEquals(nodes.length, m.size()); m = (DoubleOrderedMap) makeMap(); m1 = new HashMap(); for (int k = 0; k < nodes.length; k++) { m1.put(nodes[k].getKey(), nodes[k].getValue()); } m.putAll(m1); assertEquals(nodes.length, m.size()); for (int k = 0; k < nodes.length; k++) { assertSame(nodes[k].getValue(), m.get(nodes[k].getKey())); } } /** * test clear() method */ public void testClear() { Map m = (DoubleOrderedMap) makeMap(); LocalTestNode nodes[] = makeLocalNodes(); for (int k = 0; k < nodes.length; k++) { m.put(nodes[k].getKey(), nodes[k].getValue()); assertTrue(!m.isEmpty()); } assertTrue(!m.isEmpty()); for (int k = 0; k < nodes.length; k++) { assertTrue(m.containsKey(nodes[k].getKey())); assertTrue(m.containsValue(nodes[k].getValue())); } m.clear(); assertTrue(m.isEmpty()); for (int k = 0; k < nodes.length; k++) { assertTrue(!m.containsKey(nodes[k].getKey())); assertTrue(!m.containsValue(nodes[k].getValue())); } } /** * test keySet() method */ public void testKeySet() { testKeySet((DoubleOrderedMap) makeMap()); Map m = (DoubleOrderedMap) makeMap(); LocalTestNode nodes[] = makeLocalNodes(); for (int k = 0; k < nodes.length; k++) { m.put(nodes[k].getKey(), nodes[k]); } testKeySet(m); m = (DoubleOrderedMap) makeMap(); for (int k = 0; k < nodes.length; k++) { m.put(nodes[k].getKey(), nodes[k]); } int count = m.size(); for (Iterator iter = m.keySet().iterator(); iter.hasNext(); ) { iter.next(); iter.remove(); --count; assertEquals(count, m.size()); } assertTrue(m.isEmpty()); m = (DoubleOrderedMap) makeMap(); for (int k = 0; k < nodes.length; k++) { m.put(nodes[k].getKey(), nodes[k]); } Set s = m.keySet(); try { s.remove(null); fail("should have caught NullPointerException"); } catch (NullPointerException ignored) {} try { s.remove(new Object()); fail("should have caught ClassCastException"); } catch (ClassCastException ignored) {} for (int k = 0; k < nodes.length; k++) { Comparable key = nodes[k].getKey(); assertTrue(s.remove(key)); assertTrue(!s.contains(key)); assertTrue(!m.containsKey(key)); assertTrue(!m.containsValue(nodes[k])); } assertTrue(m.isEmpty()); m = (DoubleOrderedMap) makeMap(); Collection c1 = new LinkedList(); Collection c2 = new LinkedList(); c2.add(new Integer(-99)); for (int k = 0; k < nodes.length; k++) { m.put(nodes[k].getKey(), nodes[k]); c1.add(nodes[k].getKey()); c2.add(nodes[k].getKey()); } assertTrue(m.keySet().containsAll(c1)); assertTrue(!m.keySet().containsAll(c2)); m = (DoubleOrderedMap) makeMap(); c1 = new LinkedList(); c1.add(new Integer(-55)); try { m.keySet().addAll(c1); fail("should have caught exception of addAll()"); } catch (UnsupportedOperationException ignored) {} for (int k = 0; k < nodes.length; k++) { m.put(nodes[k].getKey(), nodes[k]); c1.add(nodes[k].getKey()); } assertTrue(!m.keySet().retainAll(c1)); assertEquals(nodes.length, m.size()); m = (DoubleOrderedMap) makeMap(); c1 = new LinkedList(); for (int k = 0; k < nodes.length; k++) { m.put(nodes[k].getKey(), nodes[k]); if (k % 2 == 1) { c1.add(nodes[k].getKey()); } } assertTrue(m.keySet().retainAll(c1)); assertEquals(nodes.length / 2, m.size()); m = (DoubleOrderedMap) makeMap(); c1 = new LinkedList(); for (int k = 0; k < nodes.length; k++) { m.put(nodes[k].getKey(), nodes[k]); } assertTrue(m.keySet().retainAll(c1)); assertEquals(0, m.size()); m = (DoubleOrderedMap) makeMap(); c1 = new LinkedList(); for (int k = 0; k < nodes.length; k++) { m.put(nodes[k].getKey(), nodes[k]); } assertTrue(!m.keySet().removeAll(c1)); assertEquals(nodes.length, m.size()); m = (DoubleOrderedMap) makeMap(); c1 = new LinkedList(); for (int k = 0; k < nodes.length; k++) { m.put(nodes[k].getKey(), nodes[k]); if (k % 2 == 0) { c1.add(nodes[k].getKey()); } } assertTrue(m.keySet().removeAll(c1)); assertEquals(nodes.length / 2, m.size()); m = (DoubleOrderedMap) makeMap(); c1 = new LinkedList(); for (int k = 0; k < nodes.length; k++) { m.put(nodes[k].getKey(), nodes[k]); c1.add(nodes[k].getKey()); } assertTrue(m.keySet().removeAll(c1)); assertEquals(0, m.size()); m = (DoubleOrderedMap) makeMap(); for (int k = 0; k < nodes.length; k++) { m.put(nodes[k].getKey(), nodes[k]); } m.keySet().clear(); assertEquals(0, m.size()); } /** * test values() method */ public void testValues() { testValues((DoubleOrderedMap) makeMap()); Map m = (DoubleOrderedMap) makeMap(); LocalTestNode nodes[] = makeLocalNodes(); for (int k = 0; k < nodes.length; k++) { m.put(nodes[k].getKey(), nodes[k]); } testValues(m); m = (DoubleOrderedMap) makeMap(); for (int k = 0; k < nodes.length; k++) { m.put(nodes[k].getKey(), nodes[k]); } int count = m.size(); for (Iterator iter = m.values().iterator(); iter.hasNext(); ) { iter.next(); iter.remove(); --count; assertEquals(count, m.size()); } assertTrue(m.isEmpty()); m = (DoubleOrderedMap) makeMap(); for (int k = 0; k < nodes.length; k++) { m.put(nodes[k].getKey(), nodes[k]); } count = m.size(); Collection s = m.values(); for (int k = 0; k < count; k++) { assertTrue(s.remove(nodes[k])); assertTrue(!s.contains(nodes[k])); assertTrue(!m.containsKey(nodes[k].getKey())); assertTrue(!m.containsValue(nodes[k])); } assertTrue(m.isEmpty()); m = (DoubleOrderedMap) makeMap(); Collection c1 = new LinkedList(); Collection c2 = new LinkedList(); c2.add(new LocalTestNode(-123)); for (int k = 0; k < nodes.length; k++) { m.put(nodes[k].getKey(), nodes[k]); c1.add(nodes[k]); c2.add(nodes[k]); } assertTrue(m.values().containsAll(c1)); assertTrue(!m.values().containsAll(c2)); m = (DoubleOrderedMap) makeMap(); c1 = new LinkedList(); for (int k = 0; k < nodes.length; k++) { m.put(nodes[k].getKey(), nodes[k]); c1.add(nodes[k]); } try { m.values().addAll(c1); fail("should have caught exception of addAll()"); } catch (UnsupportedOperationException ignored) {} m = (DoubleOrderedMap) makeMap(); c1 = new LinkedList(); for (int k = 0; k < nodes.length; k++) { m.put(nodes[k].getKey(), nodes[k]); c1.add(nodes[k]); } assertTrue(!m.values().retainAll(c1)); assertEquals(nodes.length, m.size()); m = (DoubleOrderedMap) makeMap(); c1 = new LinkedList(); for (int k = 0; k < nodes.length; k++) { m.put(nodes[k].getKey(), nodes[k]); if (k % 2 == 1) { c1.add(nodes[k]); } } assertTrue(m.values().retainAll(c1)); assertEquals(nodes.length / 2, m.size()); m = (DoubleOrderedMap) makeMap(); c1 = new LinkedList(); for (int k = 0; k < nodes.length; k++) { m.put(nodes[k].getKey(), nodes[k]); } assertTrue(m.values().retainAll(c1)); assertEquals(0, m.size()); m = (DoubleOrderedMap) makeMap(); c1 = new LinkedList(); for (int k = 0; k < nodes.length; k++) { m.put(nodes[k].getKey(), nodes[k]); } assertTrue(!m.values().removeAll(c1)); assertEquals(nodes.length, m.size()); m = (DoubleOrderedMap) makeMap(); c1 = new LinkedList(); for (int k = 0; k < nodes.length; k++) { m.put(nodes[k].getKey(), nodes[k]); if (k % 2 == 0) { c1.add(nodes[k]); } } assertTrue(m.values().removeAll(c1)); assertEquals(nodes.length / 2, m.size()); m = (DoubleOrderedMap) makeMap(); c1 = new LinkedList(); for (int k = 0; k < nodes.length; k++) { m.put(nodes[k].getKey(), nodes[k]); c1.add(nodes[k]); } assertTrue(m.values().removeAll(c1)); assertEquals(0, m.size()); m = (DoubleOrderedMap) makeMap(); for (int k = 0; k < nodes.length; k++) { m.put(nodes[k].getKey(), nodes[k]); } m.values().clear(); assertEquals(0, m.size()); } /** * test entrySet() method */ public void testEntrySet() { testEntrySet((DoubleOrderedMap) makeMap()); Map m = (DoubleOrderedMap) makeMap(); LocalTestNode nodes[] = makeLocalNodes(); for (int k = 0; k < nodes.length; k++) { m.put(nodes[k].getKey(), nodes[k]); } testEntrySet(m); m = (DoubleOrderedMap) makeMap(); for (int k = 0; k < nodes.length; k++) { m.put(nodes[k].getKey(), nodes[k]); } try { ((Map.Entry) m.entrySet().iterator().next()) .setValue(new LocalTestNode(-1)); fail("Should have caught UnsupportedOperationException"); } catch (UnsupportedOperationException ignored) {} int count = m.size(); for (Iterator iter = m.entrySet().iterator(); iter.hasNext(); ) { iter.next(); iter.remove(); --count; assertEquals(count, m.size()); } assertTrue(m.isEmpty()); m = (DoubleOrderedMap) makeMap(); Collection c1 = new LinkedList(); for (int k = 0; k < nodes.length; k++) { m.put(nodes[k].getKey(), nodes[k]); c1.add(nodes[k].getKey()); } try { m.entrySet().addAll(c1); fail("should have caught exception of addAll()"); } catch (UnsupportedOperationException ignored) {} m = (DoubleOrderedMap) makeMap(); for (int k = 0; k < nodes.length; k++) { m.put(nodes[k].getKey(), nodes[k]); } m.entrySet().clear(); assertEquals(0, m.size()); m = (DoubleOrderedMap) makeMap(); for (int k = 0; k < nodes.length; k++) { m.put(nodes[k].getKey(), nodes[k]); } int x = 0; for (Iterator iter = m.entrySet().iterator(); iter.hasNext(); ) { Map.Entry entry = (Map.Entry) iter.next(); assertSame(entry.getKey(), nodes[x].getKey()); assertSame(entry.getValue(), nodes[x]); x++; } } /** * Method testEquals */ public void testEquals() { Map m = (DoubleOrderedMap) makeMap(); LocalTestNode nodes[] = makeLocalNodes(); for (int k = 0; k < nodes.length; k++) { m.put(nodes[k].getKey(), nodes[k]); } assertTrue(!m.equals(null)); assertEquals(m, m); Map m1 = new HashMap(); for (int k = 0; k < nodes.length; k++) { m1.put(nodes[k].getKey(), nodes[k]); } assertEquals(m, m1); m1 = (DoubleOrderedMap) makeMap(); for (int k = 0; k < (nodes.length - 1); k++) { m1.put(nodes[k].getKey(), nodes[k]); } assertTrue(!m.equals(m1)); m1 = (DoubleOrderedMap) makeMap(); for (int k = 0; k < nodes.length; k++) { m1.put(nodes[k].getKey(), nodes[k]); } LocalTestNode node1 = new LocalTestNode(-1000); m1.put(node1.getKey(), node1); assertTrue(!m.equals(m1)); m1 = (DoubleOrderedMap) makeMap(); for (int k = 0; k < nodes.length; k++) { m1.put(nodes[k].getKey(), nodes[nodes.length - (k + 1)]); } assertTrue(!m.equals(m1)); m1 = (DoubleOrderedMap) makeMap(); for (int k = nodes.length - 1; k >= 0; k--) { m1.put(nodes[k].getKey(), nodes[k]); } assertEquals(m, m1); } /** * test hashCode() method */ public void testHashCode() { Map m = (DoubleOrderedMap) makeMap(); LocalTestNode nodes[] = makeLocalNodes(); for (int k = 0; k < nodes.length; k++) { m.put(nodes[k].getKey(), nodes[k]); } Map m1 = (DoubleOrderedMap) makeMap(); for (int k = nodes.length - 1; k >= 0; k--) { m1.put(nodes[k].getKey(), nodes[k]); } assertEquals(m.hashCode(), m1.hashCode()); } /** * test constructors */ public void testConstructors() { DoubleOrderedMap m = (DoubleOrderedMap) makeMap(); assertTrue(m.isEmpty()); DoubleOrderedMap m1 = new DoubleOrderedMap(m); assertTrue(m1.isEmpty()); m1 = (DoubleOrderedMap) makeMap(); LocalTestNode nodes[] = makeLocalNodes(); for (int k = 0; k < nodes.length; k++) { m1.put(nodes[k].getKey(), nodes[k]); } m = new DoubleOrderedMap(m1); assertEquals(m, m1); Map m2 = new HashMap(); for (int k = 0; k < nodes.length; k++) { m2.put(nodes[k].getKey(), nodes[k]); } m = new DoubleOrderedMap(m2); assertEquals(m, m2); // reject duplicated values m2 = new HashMap(); m2.put("1", "foo"); m2.put("2", "foo"); try { m = new DoubleOrderedMap(m2); fail("Should have caught IllegalArgumentException"); } catch (IllegalArgumentException ignored) {} // reject null values m2.put("2", null); try { m = new DoubleOrderedMap(m2); fail("Should have caught NullPointerException"); } catch (NullPointerException ignored) {} // reject non-Comparable values m2.put("2", new Object()); try { m = new DoubleOrderedMap(m2); fail("Should have caught ClassCastException"); } catch (ClassCastException ignored) {} // reject incompatible values m2.put("2", new Integer(2)); try { m = new DoubleOrderedMap(m2); fail("Should have caught ClassCastException"); } catch (ClassCastException ignored) {} // reject incompatible keys m2.remove("2"); m2.put(new Integer(2), "bad key"); try { m = new DoubleOrderedMap(m2); fail("Should have caught ClassCastException"); } catch (ClassCastException ignored) {} // reject non-Comparable keys m2.clear(); m2.put("1", "foo"); m2.put(new Object(), "bad key"); try { m = new DoubleOrderedMap(m2); fail("Should have caught ClassCastException"); } catch (ClassCastException ignored) {} } /** * test getKeyForValue() method */ public void testGetKeyForValue() { DoubleOrderedMap m = (DoubleOrderedMap) makeMap(); try { m.getKeyForValue(new Object()); fail("should have caught ClassCastException"); } catch (ClassCastException ignored) {} try { m.getKeyForValue(null); fail("should have caught NullPointerException"); } catch (NullPointerException ignored) {} assertNull(m.getKeyForValue("foo")); LocalTestNode nodes[] = makeLocalNodes(); for (int k = 0; k < nodes.length; k++) { m.put(nodes[k].getKey(), nodes[k]); assertSame(m.getKeyForValue(nodes[k]), nodes[k].getKey()); } assertNull(m.getKeyForValue(new LocalTestNode(-1))); try { m.getKeyForValue("foo"); fail("Should have caught ClassCastException"); } catch (ClassCastException ignored) {} for (int k = 0; k < nodes.length; k++) { assertNotNull(m.getKeyForValue(nodes[k])); m.remove(nodes[k].getKey()); assertNull(m.getKeyForValue(nodes[k])); } } /** * test removeValue() method */ public void testRemoveValue() { DoubleOrderedMap m = (DoubleOrderedMap) makeMap(); LocalTestNode nodes[] = makeLocalNodes(); for (int k = 0; k < nodes.length; k++) { m.put(nodes[k].getKey(), nodes[k]); } try { m.removeValue(null); fail("should have caught NullPointerException"); } catch (NullPointerException ignored) {} try { m.removeValue(new Object()); fail("should have caught ClassCastException"); } catch (ClassCastException ignored) {} assertNull(m.remove(new Integer(-1))); try { m.removeValue("foo"); fail("should have caught ClassCastException"); } catch (ClassCastException ignored) {} for (int k = 0; k < nodes.length; k += 2) { assertNotNull(m.getKeyForValue(nodes[k])); assertSame(nodes[k].getKey(), m.removeValue(nodes[k])); assertNull(m.removeValue(nodes[k])); assertNull(m.getKeyForValue(nodes[k])); } for (int k = 1; k < nodes.length; k += 2) { assertNotNull(m.getKeyForValue(nodes[k])); assertSame(nodes[k].getKey(), m.removeValue(nodes[k])); assertNull(m.removeValue(nodes[k])); assertNull(m.getKeyForValue(nodes[k])); } assertTrue(m.isEmpty()); } /** * test entrySetByValue() method */ public void testEntrySetByValue() { testEntrySetByValue((DoubleOrderedMap) makeMap()); DoubleOrderedMap m = (DoubleOrderedMap) makeMap(); LocalTestNode nodes[] = makeLocalNodes(); for (int k = 0; k < nodes.length; k++) { m.put(nodes[k].getKey(), nodes[k]); } testEntrySetByValue(m); m = (DoubleOrderedMap) makeMap(); for (int k = 0; k < nodes.length; k++) { m.put(nodes[k].getKey(), nodes[k]); } try { ((Map.Entry) m.entrySetByValue().iterator().next()) .setValue(new LocalTestNode(-1)); fail("Should have caught UnsupportedOperationException"); } catch (UnsupportedOperationException ignored) {} int count = m.size(); for (Iterator iter = m.entrySetByValue().iterator(); iter.hasNext(); ) { iter.next(); iter.remove(); --count; assertEquals(count, m.size()); } assertTrue(m.isEmpty()); m = (DoubleOrderedMap) makeMap(); Collection c1 = new LinkedList(); for (int k = 0; k < nodes.length; k++) { m.put(nodes[k].getKey(), nodes[k]); c1.add(nodes[k].getKey()); } try { m.entrySetByValue().addAll(c1); fail("should have caught exception of addAll()"); } catch (UnsupportedOperationException ignored) {} m = (DoubleOrderedMap) makeMap(); for (int k = 0; k < nodes.length; k++) { m.put(nodes[k].getKey(), nodes[k]); } m.entrySetByValue().clear(); assertEquals(0, m.size()); m = (DoubleOrderedMap) makeMap(); for (int k = 0; k < nodes.length; k++) { m.put(nodes[k].getKey(), nodes[k]); } int x = 0; for (Iterator iter = m.entrySetByValue().iterator(); iter.hasNext(); ) { Map.Entry entry = (Map.Entry) iter.next(); assertSame(entry.getKey(), nodes[x].getKey()); assertSame(entry.getValue(), nodes[x]); x++; } } /** * test keySetByValue() method */ public void testKeySetByValue() { testKeySetByValue((DoubleOrderedMap) makeMap()); DoubleOrderedMap m = (DoubleOrderedMap) makeMap(); LocalTestNode nodes[] = makeLocalNodes(); for (int k = 0; k < nodes.length; k++) { m.put(nodes[k].getKey(), nodes[k]); } testKeySetByValue(m); m = (DoubleOrderedMap) makeMap(); for (int k = 0; k < nodes.length; k++) { m.put(nodes[k].getKey(), nodes[k]); } int count = m.size(); for (Iterator iter = m.keySetByValue().iterator(); iter.hasNext(); ) { iter.next(); iter.remove(); --count; assertEquals(count, m.size()); } assertTrue(m.isEmpty()); m = (DoubleOrderedMap) makeMap(); for (int k = 0; k < nodes.length; k++) { m.put(nodes[k].getKey(), nodes[k]); } Set s = m.keySetByValue(); try { s.remove(null); fail("should have caught NullPointerException"); } catch (NullPointerException ignored) {} try { s.remove(new Object()); fail("should have caught ClassCastException"); } catch (ClassCastException ignored) {} for (int k = 0; k < nodes.length; k++) { Comparable key = nodes[k].getKey(); assertTrue(s.remove(key)); assertTrue(!s.contains(key)); assertTrue(!m.containsKey(key)); assertTrue(!m.containsValue(nodes[k])); } assertTrue(m.isEmpty()); m = (DoubleOrderedMap) makeMap(); Collection c1 = new LinkedList(); Collection c2 = new LinkedList(); c2.add(new Integer(-99)); for (int k = 0; k < nodes.length; k++) { m.put(nodes[k].getKey(), nodes[k]); c1.add(nodes[k].getKey()); c2.add(nodes[k].getKey()); } assertTrue(m.keySetByValue().containsAll(c1)); assertTrue(!m.keySetByValue().containsAll(c2)); m = (DoubleOrderedMap) makeMap(); c1 = new LinkedList(); c1.add(new Integer(-55)); try { m.keySetByValue().addAll(c1); fail("should have caught exception of addAll()"); } catch (UnsupportedOperationException ignored) {} for (int k = 0; k < nodes.length; k++) { m.put(nodes[k].getKey(), nodes[k]); c1.add(nodes[k].getKey()); } assertTrue(!m.keySetByValue().retainAll(c1)); assertEquals(nodes.length, m.size()); m = (DoubleOrderedMap) makeMap(); c1 = new LinkedList(); for (int k = 0; k < nodes.length; k++) { m.put(nodes[k].getKey(), nodes[k]); if (k % 2 == 1) { c1.add(nodes[k].getKey()); } } assertTrue(m.keySetByValue().retainAll(c1)); assertEquals(nodes.length / 2, m.size()); m = (DoubleOrderedMap) makeMap(); c1 = new LinkedList(); for (int k = 0; k < nodes.length; k++) { m.put(nodes[k].getKey(), nodes[k]); } assertTrue(m.keySetByValue().retainAll(c1)); assertEquals(0, m.size()); m = (DoubleOrderedMap) makeMap(); c1 = new LinkedList(); for (int k = 0; k < nodes.length; k++) { m.put(nodes[k].getKey(), nodes[k]); } assertTrue(!m.keySetByValue().removeAll(c1)); assertEquals(nodes.length, m.size()); m = (DoubleOrderedMap) makeMap(); c1 = new LinkedList(); for (int k = 0; k < nodes.length; k++) { m.put(nodes[k].getKey(), nodes[k]); if (k % 2 == 0) { c1.add(nodes[k].getKey()); } } assertTrue(m.keySetByValue().removeAll(c1)); assertEquals(nodes.length / 2, m.size()); m = (DoubleOrderedMap) makeMap(); c1 = new LinkedList(); for (int k = 0; k < nodes.length; k++) { m.put(nodes[k].getKey(), nodes[k]); c1.add(nodes[k].getKey()); } assertTrue(m.keySetByValue().removeAll(c1)); assertEquals(0, m.size()); m = (DoubleOrderedMap) makeMap(); for (int k = 0; k < nodes.length; k++) { m.put(nodes[k].getKey(), nodes[k]); } m.keySetByValue().clear(); assertEquals(0, m.size()); } /** * test valuesByValue() method */ public void testValuesByValue() { testValuesByValue((DoubleOrderedMap) makeMap()); DoubleOrderedMap m = (DoubleOrderedMap) makeMap(); LocalTestNode nodes[] = makeLocalNodes(); for (int k = 0; k < nodes.length; k++) { m.put(nodes[k].getKey(), nodes[k]); } testValuesByValue(m); m = (DoubleOrderedMap) makeMap(); for (int k = 0; k < nodes.length; k++) { m.put(nodes[k].getKey(), nodes[k]); } int count = m.size(); for (Iterator iter = m.valuesByValue().iterator(); iter.hasNext(); ) { iter.next(); iter.remove(); --count; assertEquals(count, m.size()); } assertTrue(m.isEmpty()); m = (DoubleOrderedMap) makeMap(); for (int k = 0; k < nodes.length; k++) { m.put(nodes[k].getKey(), nodes[k]); } count = m.size(); Collection s = m.valuesByValue(); for (int k = 0; k < count; k++) { assertTrue(s.remove(nodes[k])); assertTrue(!s.contains(nodes[k])); assertTrue(!m.containsKey(nodes[k].getKey())); assertTrue(!m.containsValue(nodes[k])); } assertTrue(m.isEmpty()); m = (DoubleOrderedMap) makeMap(); Collection c1 = new LinkedList(); Collection c2 = new LinkedList(); c2.add(new LocalTestNode(-123)); for (int k = 0; k < nodes.length; k++) { m.put(nodes[k].getKey(), nodes[k]); c1.add(nodes[k]); c2.add(nodes[k]); } assertTrue(m.valuesByValue().containsAll(c1)); assertTrue(!m.valuesByValue().containsAll(c2)); m = (DoubleOrderedMap) makeMap(); c1 = new LinkedList(); for (int k = 0; k < nodes.length; k++) { m.put(nodes[k].getKey(), nodes[k]); c1.add(nodes[k]); } try { m.valuesByValue().addAll(c1); fail("should have caught exception of addAll()"); } catch (UnsupportedOperationException ignored) {} m = (DoubleOrderedMap) makeMap(); c1 = new LinkedList(); for (int k = 0; k < nodes.length; k++) { m.put(nodes[k].getKey(), nodes[k]); c1.add(nodes[k]); } assertTrue(!m.valuesByValue().retainAll(c1)); assertEquals(nodes.length, m.size()); m = (DoubleOrderedMap) makeMap(); c1 = new LinkedList(); for (int k = 0; k < nodes.length; k++) { m.put(nodes[k].getKey(), nodes[k]); if (k % 2 == 1) { c1.add(nodes[k]); } } assertTrue(m.valuesByValue().retainAll(c1)); assertEquals(nodes.length / 2, m.size()); m = (DoubleOrderedMap) makeMap(); c1 = new LinkedList(); for (int k = 0; k < nodes.length; k++) { m.put(nodes[k].getKey(), nodes[k]); } assertTrue(m.valuesByValue().retainAll(c1)); assertEquals(0, m.size()); m = (DoubleOrderedMap) makeMap(); c1 = new LinkedList(); for (int k = 0; k < nodes.length; k++) { m.put(nodes[k].getKey(), nodes[k]); } assertTrue(!m.valuesByValue().removeAll(c1)); assertEquals(nodes.length, m.size()); m = (DoubleOrderedMap) makeMap(); c1 = new LinkedList(); for (int k = 0; k < nodes.length; k++) { m.put(nodes[k].getKey(), nodes[k]); if (k % 2 == 0) { c1.add(nodes[k]); } } assertTrue(m.valuesByValue().removeAll(c1)); assertEquals(nodes.length / 2, m.size()); m = (DoubleOrderedMap) makeMap(); c1 = new LinkedList(); for (int k = 0; k < nodes.length; k++) { m.put(nodes[k].getKey(), nodes[k]); c1.add(nodes[k]); } assertTrue(m.valuesByValue().removeAll(c1)); assertEquals(0, m.size()); m = (DoubleOrderedMap) makeMap(); for (int k = 0; k < nodes.length; k++) { m.put(nodes[k].getKey(), nodes[k]); } m.valuesByValue().clear(); assertEquals(0, m.size()); } /* ********** START helper methods ********** */ private void testKeySet(final Map m) { Set s = m.keySet(); assertEquals(m.size(), s.size()); assertEquals(m.isEmpty(), s.isEmpty()); LocalTestNode node = new LocalTestNode(-1); m.put(node.getKey(), node); assertTrue(s.contains(node.getKey())); assertEquals(m.size(), s.size()); assertEquals(m.isEmpty(), s.isEmpty()); m.remove(node.getKey()); assertTrue(!s.contains(node.getKey())); assertEquals(m.size(), s.size()); assertEquals(m.isEmpty(), s.isEmpty()); try { s.contains(null); fail("should have caught NullPointerException"); } catch (NullPointerException ignored) {} try { s.contains(new Object()); fail("should have caught ClassCastException"); } catch (ClassCastException ignored) {} for (int k = 0; k < m.size(); k++) { assertTrue(s.contains(new Integer(k))); } int count = 0; for (Iterator iter = s.iterator(); iter.hasNext(); ) { iter.next(); ++count; } assertEquals(count, s.size()); // force the map to have some content m.put(node.getKey(), node); Iterator iter = m.keySet().iterator(); LocalTestNode node2 = new LocalTestNode(-2); m.put(node2.getKey(), node2); try { iter.next(); fail("next() should have thrown an exception after a put"); } catch (ConcurrentModificationException ignored) {} m.remove(node2.getKey()); iter = s.iterator(); m.remove(node.getKey()); try { iter.next(); fail("next() should have thrown an exception after a Map remove"); } catch (ConcurrentModificationException ignored) {} m.put(node.getKey(), node); iter = s.iterator(); s.remove(node.getKey()); try { iter.next(); fail("next() should have thrown an exception after a Set remove"); } catch (ConcurrentModificationException ignored) {} iter = s.iterator(); count = 0; boolean terminated = false; try { while (true) { iter.next(); ++count; } } catch (NoSuchElementException ignored) { terminated = true; } assertTrue(terminated); assertEquals(m.size(), count); iter = s.iterator(); try { iter.remove(); fail("Should have thrown exception"); } catch (IllegalStateException ignored) {} m.put(node.getKey(), node); iter = s.iterator(); iter.next(); m.put(node2.getKey(), node2); try { iter.remove(); fail("should have thrown exception"); } catch (ConcurrentModificationException ignored) {} Iterator iter2 = s.iterator(); iter2.next(); LocalTestNode node3 = new LocalTestNode(-3); m.put(node3.getKey(), node3); try { iter2.remove(); fail("should have thrown exception"); } catch (ConcurrentModificationException ignored) {} int removalCount = 0; for (iter = s.iterator(); iter.hasNext(); ) { if (iter.next().equals(node.getKey())) { try { iter.remove(); ++removalCount; iter.remove(); fail("2nd remove should have failed"); } catch (IllegalStateException ignored) { assertEquals(1, removalCount); } } } assertEquals(1, removalCount); assertTrue(!s.contains(node.getKey())); removalCount = 0; m.put(node.getKey(), node); Object[] a1 = s.toArray(); assertEquals(s.size(), a1.length); if (a1.length > 1) { Comparable first = (Comparable) a1[0]; for (int k = 1; k < a1.length; k++) { Comparable second = (Comparable) a1[k]; assertTrue(first.compareTo(second) < 0); first = second; } iter = s.iterator(); first = (Comparable) iter.next(); for (; iter.hasNext(); ) { Comparable second = (Comparable) iter.next(); assertTrue(first.compareTo(second) < 0); first = second; } } try { String array2[] = (String[]) s.toArray(new String[0]); if (s.size() != 0) { fail("should have caught exception creating an invalid array"); } } catch (ArrayStoreException ignored) {} Comparable array2[] = (Comparable[]) s.toArray(new Comparable[0]); Integer array3[] = (Integer[]) s.toArray(new Integer[s.size()]); if (array3.length > 1) { Integer first = array3[0]; for (int k = 1; k < array3.length; k++) { Integer second = array3[k]; assertTrue(first.compareTo(second) < 0); first = second; } } try { s.add("foo"); fail("should have thrown an exception"); } catch (UnsupportedOperationException ignored) {} assertTrue(!s.equals(null)); assertEquals(s, s); Set hs = new HashSet(s); assertEquals(s, hs); assertEquals(hs, s); assertEquals(s.hashCode(), hs.hashCode()); } private void testKeySetByValue(final DoubleOrderedMap m) { Set s = m.keySetByValue(); assertEquals(m.size(), s.size()); assertEquals(m.isEmpty(), s.isEmpty()); LocalTestNode node = new LocalTestNode(-1); m.put(node.getKey(), node); assertTrue(s.contains(node.getKey())); assertEquals(m.size(), s.size()); assertEquals(m.isEmpty(), s.isEmpty()); m.remove(node.getKey()); assertTrue(!s.contains(node.getKey())); assertEquals(m.size(), s.size()); assertEquals(m.isEmpty(), s.isEmpty()); try { s.contains(null); fail("should have caught NullPointerException"); } catch (NullPointerException ignored) {} try { s.contains(new Object()); fail("should have caught ClassCastException"); } catch (ClassCastException ignored) {} for (int k = 0; k < m.size(); k++) { assertTrue(s.contains(new Integer(k))); } int count = 0; for (Iterator iter = s.iterator(); iter.hasNext(); ) { iter.next(); ++count; } assertEquals(count, s.size()); // force the map to have some content m.put(node.getKey(), node); Iterator iter = m.keySetByValue().iterator(); LocalTestNode node2 = new LocalTestNode(-2); m.put(node2.getKey(), node2); try { iter.next(); fail("next() should have thrown an exception after a put"); } catch (ConcurrentModificationException ignored) {} m.remove(node2.getKey()); iter = s.iterator(); m.remove(node.getKey()); try { iter.next(); fail("next() should have thrown an exception after a Map remove"); } catch (ConcurrentModificationException ignored) {} m.put(node.getKey(), node); iter = s.iterator(); s.remove(node.getKey()); try { iter.next(); fail("next() should have thrown an exception after a Set remove"); } catch (ConcurrentModificationException ignored) {} iter = s.iterator(); count = 0; boolean terminated = false; try { while (true) { iter.next(); ++count; } } catch (NoSuchElementException ignored) { terminated = true; } assertTrue(terminated); assertEquals(m.size(), count); iter = s.iterator(); try { iter.remove(); fail("Should have thrown exception"); } catch (IllegalStateException ignored) {} m.put(node.getKey(), node); iter = s.iterator(); iter.next(); m.put(node2.getKey(), node2); try { iter.remove(); fail("should have thrown exception"); } catch (ConcurrentModificationException ignored) {} Iterator iter2 = s.iterator(); iter2.next(); LocalTestNode node3 = new LocalTestNode(-3); m.put(node3.getKey(), node3); try { iter2.remove(); fail("should have thrown exception"); } catch (ConcurrentModificationException ignored) {} int removalCount = 0; for (iter = s.iterator(); iter.hasNext(); ) { if (iter.next().equals(node.getKey())) { try { iter.remove(); ++removalCount; iter.remove(); fail("2nd remove should have failed"); } catch (IllegalStateException ignored) { assertEquals(1, removalCount); } } } assertEquals(1, removalCount); assertTrue(!s.contains(node.getKey())); removalCount = 0; m.put(node.getKey(), node); Object[] a1 = s.toArray(); assertEquals(s.size(), a1.length); // if (a1.length > 1) // { // Comparable first = ( Comparable ) a1[ 0 ]; // for (int k = 1; k < a1.length; k++) // { // Comparable second = ( Comparable ) a1[ k ]; // assertTrue(first.compareTo(second) < 0); // first = second; // } // iter = s.iterator(); // first = ( Comparable ) iter.next(); // for (; iter.hasNext(); ) // { // Comparable second = ( Comparable ) iter.next(); // assertTrue(first.compareTo(second) < 0); // first = second; // } // } try { String array2[] = (String[]) s.toArray(new String[0]); if (s.size() != 0) { fail("should have caught exception creating an invalid array"); } } catch (ArrayStoreException ignored) {} Comparable array2[] = (Comparable[]) s.toArray(new Comparable[0]); Integer array3[] = (Integer[]) s.toArray(new Integer[s.size()]); // if (array3.length > 1) // { // Integer first = array3[ 0 ]; // for (int k = 1; k < array3.length; k++) // { // Integer second = array3[ k ]; // assertTrue(first.compareTo(second) < 0); // first = second; // } // } try { s.add("foo"); fail("should have thrown an exception"); } catch (UnsupportedOperationException ignored) {} assertTrue(!s.equals(null)); assertEquals(s, s); Set hs = new HashSet(s); assertEquals(s, hs); assertEquals(hs, s); assertEquals(s.hashCode(), hs.hashCode()); } private void testValues(Map m) { Collection s = m.values(); assertEquals(m.size(), s.size()); assertEquals(m.isEmpty(), s.isEmpty()); LocalTestNode node = new LocalTestNode(-1); m.put(node.getKey(), node); assertEquals(m.size(), s.size()); assertEquals(m.isEmpty(), s.isEmpty()); m.remove(node.getKey()); assertEquals(m.size(), s.size()); assertEquals(m.isEmpty(), s.isEmpty()); assertTrue(!s.contains(node)); for (int k = 0; k < m.size(); k++) { assertTrue(s.contains(new LocalTestNode(k))); } m.put(node.getKey(), node); assertTrue(s.contains(node)); m.remove(node.getKey()); assertTrue(!s.contains(node)); int count = 0; for (Iterator iter = s.iterator(); iter.hasNext(); ) { iter.next(); ++count; } assertEquals(s.size(), count); LocalTestNode node4 = new LocalTestNode(-4); m.put(node4.getKey(), node4); Iterator iter = s.iterator(); m.put(node.getKey(), node); try { iter.next(); fail("next() should have thrown an exception after a put"); } catch (ConcurrentModificationException ignored) {} iter = s.iterator(); m.remove(node.getKey()); try { iter.next(); fail("next() should have thrown an exception after a Map remove"); } catch (ConcurrentModificationException ignored) {} m.put(node.getKey(), node); iter = s.iterator(); s.remove(node); try { iter.next(); fail("next() should have thrown an exception after a Set remove"); } catch (ConcurrentModificationException ignored) {} iter = s.iterator(); count = 0; boolean terminated = false; try { while (true) { iter.next(); ++count; } } catch (NoSuchElementException ignored) { terminated = true; } assertTrue(terminated); assertEquals(m.size(), count); iter = s.iterator(); try { iter.remove(); fail("Should have thrown exception"); } catch (IllegalStateException ignored) {} Iterator iter2 = s.iterator(); try { iter2.remove(); fail("Should have thrown exception"); } catch (IllegalStateException ignored) {} m.put(node.getKey(), node); iter = s.iterator(); iter.next(); LocalTestNode node2 = new LocalTestNode(-2); m.put(node2.getKey(), node2); try { iter.remove(); fail("should have thrown exception"); } catch (ConcurrentModificationException ignored) {} LocalTestNode node3 = new LocalTestNode(-3); m.put(node3.getKey(), node3); iter2 = s.iterator(); while (iter2.hasNext()) { iter2.next(); } int removalCount = 0; for (iter = s.iterator(); iter.hasNext(); ) { if (iter.next().equals(node3)) { try { iter.remove(); ++removalCount; iter.remove(); fail("2nd remove should have failed"); } catch (IllegalStateException ignored) { assertEquals(1, removalCount); } } } assertEquals(1, removalCount); assertTrue(!s.contains(node3)); Object[] a1 = s.toArray(); assertEquals(s.size(), a1.length); if (a1.length > 1) { Comparable first = (Comparable) a1[0]; for (int k = 1; k < a1.length; k++) { Comparable second = (Comparable) a1[k]; assertTrue(first.compareTo(second) < 0); first = second; } iter = s.iterator(); first = (Comparable) iter.next(); for (; iter.hasNext(); ) { Comparable second = (Comparable) iter.next(); assertTrue(first.compareTo(second) < 0); first = second; } } try { String array2[] = (String[]) s.toArray(new String[0]); if (s.size() != 0) { fail("should have caught exception creating an invalid array"); } } catch (ArrayStoreException ignored) {} m.remove(node.getKey()); m.remove(node2.getKey()); m.remove(node3.getKey()); LocalTestNode array2[] = (LocalTestNode[]) s.toArray(new LocalTestNode[0]); LocalTestNode array3[] = (LocalTestNode[]) s.toArray(new LocalTestNode[s.size()]); if (array3.length > 1) { LocalTestNode first = array3[0]; for (int k = 1; k < array3.length; k++) { LocalTestNode second = array3[k]; assertTrue(first.compareTo(second) < 0); first = second; } } try { s.add(node.getKey()); fail("should have thrown an exception"); } catch (UnsupportedOperationException ignored) {} assertTrue(!s.equals(null)); assertEquals(s, s); Set hs = new HashSet(s); assertTrue(!s.equals(hs)); assertTrue(!hs.equals(s)); } private void testValuesByValue(DoubleOrderedMap m) { Collection s = m.valuesByValue(); assertEquals(m.size(), s.size()); assertEquals(m.isEmpty(), s.isEmpty()); LocalTestNode node = new LocalTestNode(-1); m.put(node.getKey(), node); assertEquals(m.size(), s.size()); assertEquals(m.isEmpty(), s.isEmpty()); m.remove(node.getKey()); assertEquals(m.size(), s.size()); assertEquals(m.isEmpty(), s.isEmpty()); assertTrue(!s.contains(node)); for (int k = 0; k < m.size(); k++) { assertTrue(s.contains(new LocalTestNode(k))); } m.put(node.getKey(), node); assertTrue(s.contains(node)); m.remove(node.getKey()); assertTrue(!s.contains(node)); int count = 0; for (Iterator iter = s.iterator(); iter.hasNext(); ) { iter.next(); ++count; } assertEquals(s.size(), count); LocalTestNode node4 = new LocalTestNode(-4); m.put(node4.getKey(), node4); Iterator iter = s.iterator(); m.put(node.getKey(), node); try { iter.next(); fail("next() should have thrown an exception after a put"); } catch (ConcurrentModificationException ignored) {} iter = s.iterator(); m.remove(node.getKey()); try { iter.next(); fail("next() should have thrown an exception after a Map remove"); } catch (ConcurrentModificationException ignored) {} m.put(node.getKey(), node); iter = s.iterator(); s.remove(node); try { iter.next(); fail("next() should have thrown an exception after a Set remove"); } catch (ConcurrentModificationException ignored) {} iter = s.iterator(); count = 0; boolean terminated = false; try { while (true) { iter.next(); ++count; } } catch (NoSuchElementException ignored) { terminated = true; } assertTrue(terminated); assertEquals(m.size(), count); iter = s.iterator(); try { iter.remove(); fail("Should have thrown exception"); } catch (IllegalStateException ignored) {} Iterator iter2 = s.iterator(); try { iter2.remove(); fail("Should have thrown exception"); } catch (IllegalStateException ignored) {} m.put(node.getKey(), node); iter = s.iterator(); iter.next(); LocalTestNode node2 = new LocalTestNode(-2); m.put(node2.getKey(), node2); try { iter.remove(); fail("should have thrown exception"); } catch (ConcurrentModificationException ignored) {} LocalTestNode node3 = new LocalTestNode(-3); m.put(node3.getKey(), node3); iter2 = s.iterator(); while (iter2.hasNext()) { iter2.next(); } int removalCount = 0; for (iter = s.iterator(); iter.hasNext(); ) { if (iter.next().equals(node3)) { try { iter.remove(); ++removalCount; iter.remove(); fail("2nd remove should have failed"); } catch (IllegalStateException ignored) { assertEquals(1, removalCount); } } } assertEquals(1, removalCount); assertTrue(!s.contains(node3)); Object[] a1 = s.toArray(); assertEquals(s.size(), a1.length); try { String array2[] = (String[]) s.toArray(new String[0]); if (s.size() != 0) { fail("should have caught exception creating an invalid array"); } } catch (ArrayStoreException ignored) {} m.remove(node.getKey()); m.remove(node2.getKey()); m.remove(node3.getKey()); LocalTestNode array2[] = (LocalTestNode[]) s.toArray(new LocalTestNode[0]); LocalTestNode array3[] = (LocalTestNode[]) s.toArray(new LocalTestNode[s.size()]); try { s.add(node.getKey()); fail("should have thrown an exception"); } catch (UnsupportedOperationException ignored) {} assertTrue(!s.equals(null)); assertEquals(s, s); Set hs = new HashSet(s); assertTrue(!s.equals(hs)); assertTrue(!hs.equals(s)); } private void testEntrySet(Map m) { Set s = m.entrySet(); assertEquals(m.size(), s.size()); assertEquals(m.isEmpty(), s.isEmpty()); LocalTestNode node = new LocalTestNode(-1); m.put(node.getKey(), node); assertEquals(m.size(), s.size()); assertEquals(m.isEmpty(), s.isEmpty()); m.remove(node.getKey()); assertEquals(m.size(), s.size()); assertEquals(m.isEmpty(), s.isEmpty()); int count = 0; for (Iterator iter = s.iterator(); iter.hasNext(); ) { iter.next(); ++count; } assertEquals(s.size(), count); LocalTestNode node2 = new LocalTestNode(-2); if (m.size() == 0) { m.put(node2.getKey(), node2); } Iterator iter = s.iterator(); m.put(node.getKey(), node); try { iter.next(); fail("next() should have thrown an exception after a put"); } catch (ConcurrentModificationException ignored) {} m.remove(node2.getKey()); iter = s.iterator(); m.remove(node.getKey()); try { iter.next(); fail("next() should have thrown an exception after a Map remove"); } catch (ConcurrentModificationException ignored) {} m.put(node.getKey(), node); iter = s.iterator(); count = 0; boolean terminated = false; try { while (true) { iter.next(); ++count; } } catch (NoSuchElementException ignored) { terminated = true; } assertTrue(terminated); assertEquals(m.size(), count); iter = s.iterator(); try { iter.remove(); fail("Should have thrown exception"); } catch (IllegalStateException ignored) {} iter = s.iterator(); iter.next(); LocalTestNode node3 = new LocalTestNode(-3); m.put(node3.getKey(), node3); try { iter.remove(); fail("should have thrown exception"); } catch (ConcurrentModificationException ignored) {} int removalCount = 0; int when = m.size() / 2; int timer = 0; for (iter = s.iterator(); iter.hasNext(); ) { iter.next(); if (timer == when) { try { iter.remove(); ++removalCount; iter.remove(); fail("2nd remove should have failed"); } catch (IllegalStateException ignored) { assertEquals(1, removalCount); } } timer++; } assertEquals(1, removalCount); Iterator iter2 = s.iterator(); try { iter2.remove(); fail("Should have thrown exception"); } catch (IllegalStateException ignored) {} iter2 = s.iterator(); while (iter2.hasNext()) { iter2.next(); } LocalTestNode node4 = new LocalTestNode(-4); m.put(node4.getKey(), node4); try { iter2.remove(); fail("should have thrown exception"); } catch (ConcurrentModificationException ignored) {} Object[] a1 = s.toArray(); assertEquals(s.size(), a1.length); if (a1.length > 1) { Map.Entry first = (Map.Entry) a1[0]; for (int k = 1; k < a1.length; k++) { Map.Entry second = (Map.Entry) a1[k]; assertTrue(((Comparable) first.getKey()) .compareTo((Comparable) second.getKey()) < 0); first = second; } iter = s.iterator(); first = (Map.Entry) iter.next(); for (; iter.hasNext(); ) { Map.Entry second = (Map.Entry) iter.next(); assertTrue(((Comparable) first.getKey()) .compareTo((Comparable) second.getKey()) < 0); first = second; } } try { Integer array2[] = (Integer[]) s.toArray(new Integer[0]); if (s.size() != 0) { fail("should have caught exception creating an invalid array"); } } catch (ArrayStoreException ignored) {} Map.Entry array2[] = (Map.Entry[]) s.toArray(new Map.Entry[0]); Map.Entry array3[] = (Map.Entry[]) s.toArray(new Map.Entry[s.size()]); if (array3.length > 1) { Comparable first = (Comparable) ((Map.Entry) array3[0]).getKey(); for (int k = 1; k < array3.length; k++) { Comparable second = (Comparable) ((Map.Entry) array3[k]).getKey(); assertTrue(first.compareTo(second) < 0); first = second; } } try { s.add(node.getKey()); fail("should have thrown an exception"); } catch (UnsupportedOperationException ignored) {} assertTrue(!s.equals(null)); assertEquals("SetEquality 1", s, s); Set hs = new HashSet(s); assertEquals("SetEquality 2", s, hs); assertEquals("SetEquality 3", hs, s); assertEquals(s.hashCode(), hs.hashCode()); } private void testEntrySetByValue(DoubleOrderedMap m) { Set s = m.entrySetByValue(); assertEquals(m.size(), s.size()); assertEquals(m.isEmpty(), s.isEmpty()); LocalTestNode node = new LocalTestNode(-1); m.put(node.getKey(), node); assertEquals(m.size(), s.size()); assertEquals(m.isEmpty(), s.isEmpty()); m.remove(node.getKey()); assertEquals(m.size(), s.size()); assertEquals(m.isEmpty(), s.isEmpty()); int count = 0; for (Iterator iter = s.iterator(); iter.hasNext(); ) { iter.next(); ++count; } assertEquals(s.size(), count); LocalTestNode node2 = new LocalTestNode(-2); if (m.size() == 0) { m.put(node2.getKey(), node2); } Iterator iter = s.iterator(); m.put(node.getKey(), node); try { iter.next(); fail("next() should have thrown an exception after a put"); } catch (ConcurrentModificationException ignored) {} m.remove(node2.getKey()); iter = s.iterator(); m.remove(node.getKey()); try { iter.next(); fail("next() should have thrown an exception after a Map remove"); } catch (ConcurrentModificationException ignored) {} m.put(node.getKey(), node); iter = s.iterator(); count = 0; boolean terminated = false; try { while (true) { iter.next(); ++count; } } catch (NoSuchElementException ignored) { terminated = true; } assertTrue(terminated); assertEquals(m.size(), count); iter = s.iterator(); try { iter.remove(); fail("Should have thrown exception"); } catch (IllegalStateException ignored) {} iter = s.iterator(); iter.next(); LocalTestNode node3 = new LocalTestNode(-3); m.put(node3.getKey(), node3); try { iter.remove(); fail("should have thrown exception"); } catch (ConcurrentModificationException ignored) {} int removalCount = 0; int when = m.size() / 2; int timer = 0; for (iter = s.iterator(); iter.hasNext(); ) { iter.next(); if (timer == when) { try { iter.remove(); ++removalCount; iter.remove(); fail("2nd remove should have failed"); } catch (IllegalStateException ignored) { assertEquals(1, removalCount); } } timer++; } assertEquals(1, removalCount); Iterator iter2 = s.iterator(); try { iter2.remove(); fail("Should have thrown exception"); } catch (IllegalStateException ignored) {} iter2 = s.iterator(); while (iter2.hasNext()) { iter2.next(); } LocalTestNode node4 = new LocalTestNode(-4); m.put(node4.getKey(), node4); try { iter2.remove(); fail("should have thrown exception"); } catch (ConcurrentModificationException ignored) {} Object[] a1 = s.toArray(); assertEquals(s.size(), a1.length); if (a1.length > 1) { Map.Entry first = (Map.Entry) a1[0]; for (int k = 1; k < a1.length; k++) { Map.Entry second = (Map.Entry) a1[k]; assertTrue(((Comparable) first.getKey()) .compareTo((Comparable) second.getKey()) < 0); first = second; } iter = s.iterator(); first = (Map.Entry) iter.next(); for (; iter.hasNext(); ) { Map.Entry second = (Map.Entry) iter.next(); assertTrue(((Comparable) first.getKey()) .compareTo((Comparable) second.getKey()) < 0); first = second; } } try { Integer array2[] = (Integer[]) s.toArray(new Integer[0]); if (s.size() != 0) { fail("should have caught exception creating an invalid array"); } } catch (ArrayStoreException ignored) {} Map.Entry array2[] = (Map.Entry[]) s.toArray(new Map.Entry[0]); Map.Entry array3[] = (Map.Entry[]) s.toArray(new Map.Entry[s.size()]); if (array3.length > 1) { Comparable first = (Comparable) ((Map.Entry) array3[0]).getValue(); for (int k = 1; k < array3.length; k++) { Comparable second = (Comparable) ((Map.Entry) array3[k]).getValue(); assertTrue(first.compareTo(second) < 0); first = second; } } try { s.add(node.getKey()); fail("should have thrown an exception"); } catch (UnsupportedOperationException ignored) {} assertTrue(!s.equals(null)); assertEquals("SetEquality 1", s, s); Set hs = new HashSet(s); assertEquals("SetEquality 2", s, hs); assertEquals("SetEquality 3", hs, s); assertEquals(s.hashCode(), hs.hashCode()); } private LocalTestNode[] makeLocalNodes() { LocalTestNode nodes[] = new LocalTestNode[1023]; for (int k = 0; k < nodes.length; k++) { nodes[k] = new LocalTestNode(k); } return nodes; } /* ********** END helper methods ********** */ /** * Method main * * @param unusedArgs */ public static void main(final String unusedArgs[]) { junit.textui.TestRunner.run(TestDoubleOrderedMap.class); } } libcommons-collections3-java.orig/src/test/org/apache/commons/collections/TestEnumerationUtils.java0000644000175000017500000000730010777673435032405 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; import java.util.ArrayList; import java.util.Hashtable; import java.util.List; import java.util.StringTokenizer; import junit.framework.Assert; import junit.framework.Test; /** * Tests EnumerationUtils. * * @author Gary Gregory * @version $Id: TestEnumerationUtils.java 646780 2008-04-10 12:48:07Z niallp $ */ 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); } } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/TestExtendedProperties.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/TestExtendedProperties.jav0000644000175000017500000003050010777673435032550 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.Properties; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * Tests some basic functions of the ExtendedProperties class. * * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Geir Magnusson Jr. * @author Mohan Kishore * @author Stephen Colebourne * @author Shinobu Kawai * @author Henning P. Schmiedehausen */ 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/list */ eprop.addProperty("number", "2"); assertTrue("This returns array", (eprop.getVector("number") instanceof java.util.Vector)); assertTrue("This returns array", (eprop.getList("number") instanceof java.util.List)); /* * now test dan's new fix where we get the first scalar * when we access a vector/list 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)); assertTrue("This returns list", (eprop.getList("prop.string") instanceof java.util.List)); 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)); assertTrue("This returns array for subset", (subEprop.getList("string") instanceof java.util.List)); } 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)); assertEquals("Commas not interpreted properly", 2, ep1.getList("three").size()); assertEquals("Commas not interpreted properly", "Hello", ep1.getList("three").get(0)); assertEquals("Commas not interpreted properly", "World", ep1.getList("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)); assertEquals(3, ep1.getList("one").size()); assertEquals("a", ep1.getList("one").get(0)); assertEquals("b", ep1.getList("one").get(1)); assertEquals("c", ep1.getList("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)); assertEquals(4, ep1.getList("one").size()); assertEquals("a", ep1.getList("one").get(0)); assertEquals("b", ep1.getList("one").get(1)); assertEquals("c", ep1.getList("one").get(2)); assertEquals("d", ep1.getList("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)); assertEquals(3, ep1.getList("one").size()); assertEquals("a", ep1.getList("one").get(0)); assertEquals("b", ep1.getList("one").get(1)); assertEquals("c", ep1.getList("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)); assertEquals(1, ep1.getList("one").size()); assertEquals("a", ep1.getList("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)); assertEquals(2, ep1.getList("one").size()); assertEquals("a", ep1.getList("one").get(0)); assertEquals(Boolean.TRUE, ep1.getList("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)); assertEquals(4, ep1.getList("one").size()); assertEquals("a", ep1.getList("one").get(0)); assertEquals(Boolean.TRUE, ep1.getList("one").get(1)); assertEquals("c", ep1.getList("one").get(2)); assertEquals("d", ep1.getList("one").get(3)); } public void testInheritDefaultProperties() { Properties defaults = new Properties(); defaults.setProperty("resource.loader", "class"); Properties properties = new Properties(defaults); properties.setProperty("test", "foo"); ExtendedProperties extended = ExtendedProperties.convertProperties(properties); assertEquals("foo", extended.getString("test")); assertEquals("class", extended.getString("resource.loader")); } } libcommons-collections3-java.orig/src/test/org/apache/commons/collections/TestFactoryUtils.java0000644000175000017500000002430410777673435031531 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.NotSerializableException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.Date; import java.util.TimeZone; import junit.framework.Test; import junit.framework.TestSuite; import junit.textui.TestRunner; import org.apache.commons.collections.functors.ConstantFactory; /** * Tests the org.apache.commons.collections.FactoryUtils class. * * @since Commons Collections 3.0 * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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); } } libcommons-collections3-java.orig/src/test/org/apache/commons/collections/TestFastArrayList.java0000644000175000017500000001275110777673435031634 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; import java.util.ArrayList; import java.util.ConcurrentModificationException; import java.util.List; import java.util.ListIterator; import junit.framework.Test; /** * Test FastArrayList. * * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Jason van Zyl */ 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); } public void testConcurrentModification_alwaysFast() { FastArrayList list = new FastArrayList(); list.setFast(true); list.add("a"); list.add("b"); list.add("c"); ListIterator iter = list.listIterator(); assertEquals("a", iter.next()); assertEquals("b", iter.next()); iter.remove(); // checking for no ConcurrentModificationException assertEquals("c", iter.next()); assertEquals(false, iter.hasNext()); assertEquals("c", iter.previous()); assertEquals("a", iter.previous()); assertEquals(false, iter.hasPrevious()); } public void testConcurrentModification_alwaysFastModError() { FastArrayList list = new FastArrayList(); list.setFast(true); list.add("a"); list.add("b"); list.add("c"); ListIterator iter = list.listIterator(); assertEquals("a", iter.next()); assertEquals("b", iter.next()); list.remove(1); try { iter.remove(); } catch (ConcurrentModificationException ex) { // expected } // iterator state now invalid } public void testConcurrentModification_delayedFast() { FastArrayList list = new FastArrayList(); list.add("a"); list.add("b"); list.add("c"); ListIterator iter = list.listIterator(); assertEquals("a", iter.next()); assertEquals("b", iter.next()); list.setFast(true); iter.remove(); // checking for no ConcurrentModificationException assertEquals("c", iter.next()); assertEquals(false, iter.hasNext()); assertEquals("c", iter.previous()); assertEquals("a", iter.previous()); assertEquals(false, iter.hasPrevious()); } public void testConcurrentModification_delayedFastModError() { FastArrayList list = new FastArrayList(); list.add("a"); list.add("b"); list.add("c"); ListIterator iter = list.listIterator(); assertEquals("a", iter.next()); assertEquals("b", iter.next()); list.setFast(true); list.remove(1); try { iter.remove(); } catch (ConcurrentModificationException ex) { // expected } // iterator state now invalid } public void testConcurrentModification_alwaysFastPrevious() { FastArrayList list = new FastArrayList(); list.setFast(true); list.add("a"); list.add("b"); list.add("c"); ListIterator iter = list.listIterator(); assertEquals("a", iter.next()); assertEquals("b", iter.next()); assertEquals("b", iter.previous()); iter.remove(); // checking for no ConcurrentModificationException assertEquals("c", iter.next()); assertEquals(false, iter.hasNext()); assertEquals("c", iter.previous()); assertEquals("a", iter.previous()); assertEquals(false, iter.hasPrevious()); } public void testConcurrentModification_alwaysFastModErrorPrevious() { FastArrayList list = new FastArrayList(); list.setFast(true); list.add("a"); list.add("b"); list.add("c"); ListIterator iter = list.listIterator(); assertEquals("a", iter.next()); assertEquals("b", iter.next()); assertEquals("b", iter.previous()); list.remove(1); try { iter.remove(); } catch (ConcurrentModificationException ex) { // expected } // iterator state now invalid } } libcommons-collections3-java.orig/src/test/org/apache/commons/collections/TestFastArrayList1.java0000644000175000017500000000661310777673435031715 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; import java.util.ArrayList; import java.util.ConcurrentModificationException; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import junit.framework.Test; /** * Test FastArrayList implementation in fast mode. * * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Jason van Zyl */ 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 void testIterateModify1() { List list = makeEmptyList(); list.add("A"); list.add("B"); list.add("C"); assertEquals(3, list.size()); Iterator it = list.iterator(); assertEquals("A", it.next()); assertEquals(3, list.size()); list.add(1, "Z"); assertEquals(4, list.size()); assertEquals("B", it.next()); assertEquals("C", it.next()); assertEquals(false, it.hasNext()); } public void testIterateModify2() { List list = makeEmptyList(); list.add("A"); list.add("B"); list.add("C"); assertEquals(3, list.size()); ListIterator it = list.listIterator(); assertEquals("A", it.next()); it.add("M"); // change via Iterator interface assertEquals(4, list.size()); list.add(2, "Z"); // change via List interface assertEquals(5, list.size()); assertEquals("B", it.next()); try { it.set("N"); // fails as previously changed via List interface fail(); } catch (ConcurrentModificationException ex) {} try { it.remove(); fail(); } catch (ConcurrentModificationException ex) {} try { it.add("N"); fail(); } catch (ConcurrentModificationException ex) {} assertEquals("C", it.next()); assertEquals(false, it.hasNext()); } } libcommons-collections3-java.orig/src/test/org/apache/commons/collections/TestFastHashMap.java0000644000175000017500000000326210777673435031240 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; import java.util.Map; import junit.framework.Test; import org.apache.commons.collections.map.AbstractTestMap; /** * Tests FastHashMap. * * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Jason van Zyl */ 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); } } libcommons-collections3-java.orig/src/test/org/apache/commons/collections/TestFastHashMap1.java0000644000175000017500000000337310777673435031324 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; import java.util.HashMap; import java.util.Map; import junit.framework.Test; /** * Test FastHashMap in fast mode. * * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Jason van Zyl */ 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(); } } libcommons-collections3-java.orig/src/test/org/apache/commons/collections/TestFastTreeMap.java0000644000175000017500000000371610777673435031260 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; import java.util.Map; import java.util.TreeMap; import junit.framework.Test; /** * Tests FastTreeMap. * * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Jason van Zyl */ 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(); } } libcommons-collections3-java.orig/src/test/org/apache/commons/collections/TestFastTreeMap1.java0000644000175000017500000000344310777673435031336 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; import java.util.Map; import java.util.TreeMap; import junit.framework.Test; /** * Test FastTreeMap in fast mode. * * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Jason van Zyl */ 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(); } } libcommons-collections3-java.orig/src/test/org/apache/commons/collections/TestHashBag.java0000644000175000017500000000324310777673435030375 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.collections.bag.AbstractTestBag; /** * Extension of {@link TestBag} for exercising the {@link HashBag} * implementation. * * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Chuck Burdick */ 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(); } } libcommons-collections3-java.orig/src/test/org/apache/commons/collections/TestIteratorUtils.java0000644000175000017500000006707210777673435031724 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.NoSuchElementException; import junit.framework.Test; import org.apache.commons.collections.iterators.EmptyIterator; import org.apache.commons.collections.iterators.EmptyListIterator; import org.apache.commons.collections.iterators.EmptyMapIterator; import org.apache.commons.collections.iterators.EmptyOrderedIterator; import org.apache.commons.collections.iterators.EmptyOrderedMapIterator; /** * Tests for IteratorUtils. * * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Unknown */ 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. } } } libcommons-collections3-java.orig/src/test/org/apache/commons/collections/TestLinkedList.java0000644000175000017500000001602410777673435031143 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; import java.util.Arrays; import java.util.Collection; import java.util.LinkedList; import java.util.List; import java.util.NoSuchElementException; import org.apache.commons.collections.list.AbstractTestList; /** * 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. * * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Rich Dougherty */ 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; } } libcommons-collections3-java.orig/src/test/org/apache/commons/collections/TestListUtils.java0000644000175000017500000001335310777673435031037 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import junit.framework.Test; import org.apache.commons.collections.list.PredicatedList; /** * Tests for ListUtils. * * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne * @author Neil O'Toole * @author Matthew Hawthorne */ public class TestListUtils extends BulkTest { private static final String a = "a"; private static final String b = "b"; private static final String c = "c"; private static final String d = "d"; private static final String e = "e"; private static final String x = "x"; private String[] fullArray; private List fullList; public TestListUtils(String name) { super(name); } public static Test suite() { return BulkTest.makeSuite(TestListUtils.class); } public void setUp() { fullArray = new String[]{a, b, c, d, e}; fullList = new ArrayList(Arrays.asList(fullArray)); } 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)); } public void testRetainAll() { List sub = new ArrayList(); sub.add(a); sub.add(b); sub.add(x); List retained = ListUtils.retainAll(fullList, sub); assertTrue(retained.size() == 2); sub.remove(x); assertTrue(retained.equals(sub)); fullList.retainAll(sub); assertTrue(retained.equals(fullList)); try { List list = ListUtils.retainAll(null, null); fail("expecting NullPointerException"); } catch(NullPointerException npe){} // this is what we want } public void testRemoveAll() { List sub = new ArrayList(); sub.add(a); sub.add(b); sub.add(x); List remainder = ListUtils.removeAll(fullList, sub); assertTrue(remainder.size() == 3); fullList.removeAll(sub); assertTrue(remainder.equals(fullList)); try { List list = ListUtils.removeAll(null, null); fail("expecting NullPointerException"); } catch(NullPointerException npe) {} // this is what we want } } libcommons-collections3-java.orig/src/test/org/apache/commons/collections/TestLRUMap.java0000644000175000017500000001576710777673435030216 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; import junit.framework.Test; /** * Tests LRUMap. * * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author James Strachan * @author Morgan Delagrange * @author Stephen Colebourne */ public class TestLRUMap extends TestSequencedHashMap { public TestLRUMap(String testName) { super(testName); } public static Test suite() { return BulkTest.makeSuite(TestLRUMap.class); } public static void main(String args[]) { String[] testCaseName = { TestLRUMap.class.getName() }; junit.textui.TestRunner.main(testCaseName); } //----------------------------------------------------------------------- public Map makeEmptyMap() { LRUMap map = new LRUMap(); return map; } /** * Override as test uses iterator() and getKey() in combination which doesn't work. */ public String[] ignoredTests() { return new String[] {"TestLRUMap.bulkTestMapEntrySet.testMapEntrySetIteratorEntry"}; } //----------------------------------------------------------------------- public void testRemoveLRU() { LRUMap map2 = new LRUMap(3); map2.put(new Integer(1),"foo"); map2.put(new Integer(2),"foo"); map2.put(new Integer(3),"foo"); map2.put(new Integer(4),"foo"); // removes 1 since max size exceeded map2.removeLRU(); // should be Integer(2) assertTrue("Second to last value should exist",map2.get(new Integer(3)).equals("foo")); assertTrue("First value inserted should not exist", map2.get(new Integer(1)) == null); } public void testMultiplePuts() { LRUMap map2 = new LRUMap(2); map2.put(new Integer(1),"foo"); map2.put(new Integer(2),"bar"); map2.put(new Integer(3),"foo"); map2.put(new Integer(4),"bar"); assertTrue("last value should exist",map2.get(new Integer(4)).equals("bar")); assertTrue("LRU should not exist", map2.get(new Integer(1)) == null); } /** * Confirm that putAll(Map) does not cause the LRUMap * to exceed its maxiumum size. */ public void testPutAll() { LRUMap map2 = new LRUMap(3); map2.put(new Integer(1),"foo"); map2.put(new Integer(2),"foo"); map2.put(new Integer(3),"foo"); HashMap hashMap = new HashMap(); hashMap.put(new Integer(4),"foo"); map2.putAll(hashMap); assertTrue("max size is 3, but actual size is " + map2.size(), map2.size() == 3); assertTrue("map should contain the Integer(4) object", map2.containsKey(new Integer(4))); } /** * Test that the size of the map is reduced immediately * when setMaximumSize(int) is called */ public void testSetMaximumSize() { LRUMap map = new LRUMap(6); map.put("1","1"); map.put("2","2"); map.put("3","3"); map.put("4","4"); map.put("5","5"); map.put("6","6"); map.setMaximumSize(3); assertTrue("map should have size = 3, but actually = " + map.size(), map.size() == 3); } public void testGetPromotion() { LRUMap map = new LRUMap(3); map.put("1","1"); map.put("2","2"); map.put("3","3"); // LRU is now 1 (then 2 then 3) // promote 1 to top // eviction order is now 2,3,1 map.get("1"); // add another value, forcing a remove // 2 should be evicted (then 3,1,4) map.put("4","4"); Iterator keyIterator = map.keySet().iterator(); Object[] keys = new Object[3]; for (int i = 0; keyIterator.hasNext() ; ++i) { keys[i] = keyIterator.next(); } assertTrue("first evicted should be 3, was " + keys[0], keys[0].equals("3")); assertTrue("second evicted should be 1, was " + keys[1], keys[1].equals("1")); assertTrue("third evicted should be 4, was " + keys[2], keys[2].equals("4")); } /** * You should be able to subclass LRUMap and perform a * custom action when items are removed automatically * by the LRU algorithm (the removeLRU() method). */ public void testLRUSubclass() { LRUCounter counter = new LRUCounter(3); // oldest <--> newest // 1 counter.put("1","foo"); // 1 2 counter.put("2","foo"); // 1 2 3 counter.put("3","foo"); // 2 3 1 counter.put("1","foo"); // 3 1 4 (2 goes out) counter.put("4","foo"); // 1 4 5 (3 goes out) counter.put("5","foo"); // 4 5 2 (1 goes out) counter.put("2","foo"); // 4 2 counter.remove("5"); assertTrue("size should be 2, but was " + counter.size(), counter.size() == 2); assertTrue("removedCount should be 3 but was " + counter.removedCount, counter.removedCount == 3); assertTrue("first removed was '2'",counter.list.get(0).equals("2")); assertTrue("second removed was '3'",counter.list.get(1).equals("3")); assertTrue("third removed was '1'",counter.list.get(2).equals("1")); assertTrue("oldest key is '4'",counter.get(0).equals("4")); assertTrue("newest key is '2'",counter.get(1).equals("2")); } protected void entrySetEqualsMap(Set set, Map m) { // Overridden because LRUMap.get(Object) actually alters the map, // so there's no way to verify that the entry set and map contain // the same entries } private class LRUCounter extends LRUMap { int removedCount = 0; ArrayList list = new ArrayList(3); LRUCounter(int i) { super(i); } protected void processRemovedLRU(Object key, Object value) { ++removedCount; list.add(key); } } } libcommons-collections3-java.orig/src/test/org/apache/commons/collections/TestMapUtils.java0000644000175000017500000007006710777673435030646 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.ListResourceBundle; import java.util.Map; import java.util.ResourceBundle; import java.util.Set; import java.util.TreeMap; import junit.framework.Test; import org.apache.commons.collections.keyvalue.DefaultKeyValue; import org.apache.commons.collections.keyvalue.DefaultMapEntry; import org.apache.commons.collections.map.LazyMap; import org.apache.commons.collections.map.PredicatedMap; import org.apache.commons.collections.map.TestPredicatedMap; /** * Tests for MapUtils. * * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne * @author Arun Mammen Thomas * @author Max Rydahl Andersen * @author Janek Bogucki * @author Neil O'Toole */ 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 testPutAll_Map_array() { try { MapUtils.putAll(null, null); fail(); } catch (NullPointerException ex) {} try { MapUtils.putAll(null, new Object[0]); fail(); } catch (NullPointerException ex) {} Map test = MapUtils.putAll(new HashMap(), new String[0]); assertEquals(0, test.size()); // sub array test = MapUtils.putAll(new HashMap(), new String[][] { {"RED", "#FF0000"}, {"GREEN", "#00FF00"}, {"BLUE", "#0000FF"} }); assertEquals(true, test.containsKey("RED")); assertEquals("#FF0000", test.get("RED")); assertEquals(true, test.containsKey("GREEN")); assertEquals("#00FF00", test.get("GREEN")); assertEquals(true, test.containsKey("BLUE")); assertEquals("#0000FF", test.get("BLUE")); assertEquals(3, test.size()); try { MapUtils.putAll(new HashMap(), new String[][] { {"RED", "#FF0000"}, null, {"BLUE", "#0000FF"} }); fail(); } catch (IllegalArgumentException ex) {} try { MapUtils.putAll(new HashMap(), new String[][] { {"RED", "#FF0000"}, {"GREEN"}, {"BLUE", "#0000FF"} }); fail(); } catch (IllegalArgumentException ex) {} try { MapUtils.putAll(new HashMap(), new String[][] { {"RED", "#FF0000"}, {}, {"BLUE", "#0000FF"} }); fail(); } catch (IllegalArgumentException ex) {} // flat array test = MapUtils.putAll(new HashMap(), new String[] { "RED", "#FF0000", "GREEN", "#00FF00", "BLUE", "#0000FF" }); assertEquals(true, test.containsKey("RED")); assertEquals("#FF0000", test.get("RED")); assertEquals(true, test.containsKey("GREEN")); assertEquals("#00FF00", test.get("GREEN")); assertEquals(true, test.containsKey("BLUE")); assertEquals("#0000FF", test.get("BLUE")); assertEquals(3, test.size()); test = MapUtils.putAll(new HashMap(), new String[] { "RED", "#FF0000", "GREEN", "#00FF00", "BLUE", "#0000FF", "PURPLE" // ignored }); assertEquals(true, test.containsKey("RED")); assertEquals("#FF0000", test.get("RED")); assertEquals(true, test.containsKey("GREEN")); assertEquals("#00FF00", test.get("GREEN")); assertEquals(true, test.containsKey("BLUE")); assertEquals("#0000FF", test.get("BLUE")); assertEquals(3, test.size()); // map entry test = MapUtils.putAll(new HashMap(), new Object[] { new DefaultMapEntry("RED", "#FF0000"), new DefaultMapEntry("GREEN", "#00FF00"), new DefaultMapEntry("BLUE", "#0000FF") }); assertEquals(true, test.containsKey("RED")); assertEquals("#FF0000", test.get("RED")); assertEquals(true, test.containsKey("GREEN")); assertEquals("#00FF00", test.get("GREEN")); assertEquals(true, test.containsKey("BLUE")); assertEquals("#0000FF", test.get("BLUE")); assertEquals(3, test.size()); // key value test = MapUtils.putAll(new HashMap(), new Object[] { new DefaultKeyValue("RED", "#FF0000"), new DefaultKeyValue("GREEN", "#00FF00"), new DefaultKeyValue("BLUE", "#0000FF") }); assertEquals(true, test.containsKey("RED")); assertEquals("#FF0000", test.get("RED")); assertEquals(true, test.containsKey("GREEN")); assertEquals("#00FF00", test.get("GREEN")); assertEquals(true, test.containsKey("BLUE")); assertEquals("#0000FF", test.get("BLUE")); assertEquals(3, test.size()); } 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()); } //----------------------------------------------------------------------- public void testIsEmptyWithEmptyMap() { Map map = new HashMap(); assertEquals(true, MapUtils.isEmpty(map)); } public void testIsEmptyWithNonEmptyMap() { Map map = new HashMap(); map.put("item", "value"); assertEquals(false, MapUtils.isEmpty(map)); } public void testIsEmptyWithNull() { Map map = null; assertEquals(true, MapUtils.isEmpty(map)); } public void testIsNotEmptyWithEmptyMap() { Map map = new HashMap(); assertEquals(false, MapUtils.isNotEmpty(map)); } public void testIsNotEmptyWithNonEmptyMap() { Map map = new HashMap(); map.put("item", "value"); assertEquals(true, MapUtils.isNotEmpty(map)); } public void testIsNotEmptyWithNull() { Map map = null; assertEquals(false, MapUtils.isNotEmpty(map)); } } libcommons-collections3-java.orig/src/test/org/apache/commons/collections/TestMultiHashMap.java0000644000175000017500000004006310777673435031435 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.collections.map.AbstractTestMap; /** * Unit Tests for MultiHashMap. * * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Unknown */ public class TestMultiHashMap extends AbstractTestMap { 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 Map 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 collections of values instead). public void verifyMap() { // TODO: implement test to ensure that map is the same as confirmed if // its values were converted into collections. } 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_Map1() { MultiMap original = new MultiHashMap(); original.put("key", "object1"); original.put("key", "object2"); MultiHashMap test = new MultiHashMap(); test.put("keyA", "objectA"); test.put("key", "object0"); test.putAll(original); assertEquals(2, test.size()); assertEquals(4, test.totalSize()); assertEquals(1, test.getCollection("keyA").size()); assertEquals(3, test.getCollection("key").size()); assertEquals(true, test.containsValue("objectA")); assertEquals(true, test.containsValue("object0")); assertEquals(true, test.containsValue("object1")); assertEquals(true, test.containsValue("object2")); } public void testPutAll_Map2() { Map original = new HashMap(); original.put("keyX", "object1"); original.put("keyY", "object2"); MultiHashMap test = new MultiHashMap(); test.put("keyA", "objectA"); test.put("keyX", "object0"); test.putAll(original); assertEquals(3, test.size()); assertEquals(4, test.totalSize()); assertEquals(1, test.getCollection("keyA").size()); assertEquals(2, test.getCollection("keyX").size()); assertEquals(1, test.getCollection("keyY").size()); assertEquals(true, test.containsValue("objectA")); assertEquals(true, test.containsValue("object0")); assertEquals(true, test.containsValue("object1")); assertEquals(true, test.containsValue("object2")); } 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()); } public void testRemove_KeyItem() { MultiHashMap map = new MultiHashMap(); map.put("A", "AA"); map.put("A", "AB"); map.put("A", "AC"); assertEquals(null, map.remove("C", "CA")); assertEquals(null, map.remove("A", "AD")); assertEquals("AC", map.remove("A", "AC")); assertEquals("AB", map.remove("A", "AB")); assertEquals("AA", map.remove("A", "AA")); assertEquals(new MultiHashMap(), map); } } libcommons-collections3-java.orig/src/test/org/apache/commons/collections/TestPredicateUtils.java0000644000175000017500000010421410777673435032021 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import junit.framework.Test; import junit.framework.TestSuite; import junit.textui.TestRunner; /** * Tests the org.apache.commons.collections.PredicateUtils class. * * @since Commons Collections 3.0 * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne * @author Matt Benson */ public class TestPredicateUtils 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 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)); 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)); 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() { assertTrue(PredicateUtils.allPredicate( new Predicate[] {}).evaluate(null)); 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)); coll.clear(); coll.add(PredicateUtils.falsePredicate()); assertFalse(PredicateUtils.allPredicate(coll).evaluate(null)); coll.clear(); coll.add(PredicateUtils.truePredicate()); assertTrue(PredicateUtils.allPredicate(coll).evaluate(null)); coll.clear(); assertTrue(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() { PredicateUtils.allPredicate(Collections.EMPTY_LIST); } 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() { assertFalse(PredicateUtils.anyPredicate( new Predicate[] {}).evaluate(null)); 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)); coll.clear(); coll.add(PredicateUtils.falsePredicate()); assertFalse(PredicateUtils.anyPredicate(coll).evaluate(null)); coll.clear(); coll.add(PredicateUtils.truePredicate()); assertTrue(PredicateUtils.anyPredicate(coll).evaluate(null)); coll.clear(); assertFalse(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() { PredicateUtils.anyPredicate(Collections.EMPTY_LIST); } 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() { assertFalse(PredicateUtils.onePredicate( new Predicate[] {}).evaluate(null)); 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)); coll.clear(); coll.add(PredicateUtils.falsePredicate()); assertFalse(PredicateUtils.onePredicate(coll).evaluate(null)); coll.clear(); coll.add(PredicateUtils.truePredicate()); assertTrue(PredicateUtils.onePredicate(coll).evaluate(null)); coll.clear(); assertFalse(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() { PredicateUtils.onePredicate(Collections.EMPTY_LIST); } 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() { assertTrue(PredicateUtils.nonePredicate( new Predicate[] {}).evaluate(null)); 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)); coll.clear(); coll.add(PredicateUtils.falsePredicate()); assertTrue(PredicateUtils.nonePredicate(coll).evaluate(null)); coll.clear(); coll.add(PredicateUtils.truePredicate()); assertFalse(PredicateUtils.nonePredicate(coll).evaluate(null)); coll.clear(); assertTrue(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() { PredicateUtils.nonePredicate(Collections.EMPTY_LIST); } 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)); assertEquals(false, PredicateUtils.instanceofPredicate(String.class).evaluate(cObject)); assertEquals(true, PredicateUtils.instanceofPredicate(String.class).evaluate(cString)); assertEquals(false, PredicateUtils.instanceofPredicate(String.class).evaluate(cInteger)); } // 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) {} } } libcommons-collections3-java.orig/src/test/org/apache/commons/collections/TestReferenceMap.java0000644000175000017500000001563410777673435031443 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; import java.lang.ref.WeakReference; import java.util.Map; import junit.framework.Test; import org.apache.commons.collections.map.AbstractTestMap; /** * Tests for ReferenceMap. * * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Paul Jack * @author Guilhem Lavaux */ public class TestReferenceMap extends AbstractTestMap { 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 "2.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); } } */ WeakReference keyReference; WeakReference valueReference; public Map buildRefMap() { Object key = new Object(); Object value = new Object(); keyReference = new WeakReference(key); 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()); return testMap; } /** Tests whether purge values setting works */ public void testPurgeValues() throws Exception { // many thanks to Juozas Baliuka for suggesting this method Map testMap = buildRefMap(); 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 } } } libcommons-collections3-java.orig/src/test/org/apache/commons/collections/TestSequencedHashMap.java0000644000175000017500000001673310777673435032266 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; import java.io.IOException; import java.io.Serializable; import java.util.Iterator; import java.util.List; import java.util.Map; import junit.framework.Test; import org.apache.commons.collections.map.AbstractTestMap; /** * Unit tests * {@link org.apache.commons.collections.SequencedHashMap}. * Be sure to use the "labRat" instance whenever possible, * so that subclasses will be tested correctly. * * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Morgan Delagrange * @author Daniel Rall * @author Henning P. Schmiedehausen * @author James Strachan */ public class TestSequencedHashMap extends AbstractTestMap { /** * The instance to experiment on. */ protected SequencedHashMap labRat; public TestSequencedHashMap(String name) { super(name); } public static Test suite() { return BulkTest.makeSuite(TestSequencedHashMap.class); } // current versions of SequencedHashMap and subclasses are not // compatible with Collections 1.x public String getCompatibilityVersion() { return "2"; } public static void main(String[] args) { String[] testCaseName = { TestSequencedHashMap.class.getName() }; junit.textui.TestRunner.main(testCaseName); } public void setUp() throws Exception { super.setUp(); // use makeMap and cast the result to a SeqHashMap // so that subclasses of SeqHashMap can share these tests labRat = (SequencedHashMap) makeEmptyMap(); } public Map makeEmptyMap() { return new SequencedHashMap(); } protected Object[] getKeys() { return new Object[] { "foo", "baz", "eek" }; } protected Object[] getValues() { return new Object[] { "bar", "frob", new Object() }; } public void testSequenceMap() throws Throwable { Object[] keys = getKeys(); int expectedSize = keys.length; Object[] values = getValues(); for (int i = 0; i < expectedSize; i++) { labRat.put(keys[i], values[i]); } // Test size(). assertEquals("size() does not match expected size", expectedSize, labRat.size()); // Test clone(), iterator(), and get(Object). SequencedHashMap clone = (SequencedHashMap) labRat.clone(); assertEquals("Size of clone does not match original", labRat.size(), clone.size()); Iterator origEntries = labRat.entrySet().iterator(); Iterator copiedEntries = clone.entrySet().iterator(); while (origEntries.hasNext()) { Map.Entry origEntry = (Map.Entry)origEntries.next(); Map.Entry copiedEntry = (Map.Entry)copiedEntries.next(); assertEquals("Cloned key does not match original", origEntry.getKey(), copiedEntry.getKey()); assertEquals("Cloned value does not match original", origEntry.getValue(), copiedEntry.getValue()); assertEquals("Cloned entry does not match original", origEntry, copiedEntry); } assertTrue("iterator() returned different number of elements than keys()", !copiedEntries.hasNext()); // Test sequence() List seq = labRat.sequence(); assertEquals("sequence() returns more keys than in the Map", expectedSize, seq.size()); for (int i = 0; i < seq.size(); i++) { assertEquals("Key " + i + " is not the same as the key in the Map", keys[i], seq.get(i)); } } public void testYoungest() { labRat.put(new Integer(1),"foo"); labRat.put(new Integer(2),"bar"); assertTrue("first key is correct",labRat.get(0).equals(new Integer(1))); labRat.put(new Integer(1),"boo"); assertTrue("second key is reassigned to first",labRat.get(0).equals(new Integer(2))); } public void testYoungestReplaceNullWithValue() { labRat.put(new Integer(1),null); labRat.put(new Integer(2),"foo"); assertTrue("first key is correct",labRat.get(0).equals(new Integer(1))); labRat.put(new Integer(1),"bar"); assertTrue("second key is reassigned to first",labRat.get(0).equals(new Integer(2))); } public void testYoungestReplaceValueWithNull() { labRat.put(new Integer(1),"bar"); labRat.put(new Integer(2),"foo"); assertTrue("first key is correct",labRat.get(0).equals(new Integer(1))); labRat.put(new Integer(1),null); assertTrue("second key is reassigned to first",labRat.get(0).equals(new Integer(2))); } // override TestMap method with more specific tests public void testFullMapSerialization() throws IOException, ClassNotFoundException { SequencedHashMap map = (SequencedHashMap) makeFullMap(); if (!(map instanceof Serializable)) return; byte[] objekt = writeExternalFormToBytes((Serializable) map); SequencedHashMap map2 = (SequencedHashMap) readExternalFormFromBytes(objekt); assertEquals("Both maps are same size",map.size(), getSampleKeys().length); assertEquals("Both maps are same size",map2.size(),getSampleKeys().length); assertEquals("Both maps have the same first key", map.getFirstKey(),getSampleKeys()[0]); assertEquals("Both maps have the same first key", map2.getFirstKey(),getSampleKeys()[0]); assertEquals("Both maps have the same last key", map.getLastKey(),getSampleKeys()[getSampleKeys().length - 1]); assertEquals("Both maps have the same last key", map2.getLastKey(),getSampleKeys()[getSampleKeys().length - 1]); } public void testIndexOf() throws Exception { Object[] keys = getKeys(); int expectedSize = keys.length; Object[] values = getValues(); for (int i = 0; i < expectedSize; i++) { labRat.put(keys[i], values[i]); } // test that the index returned are in the same order that they were // placed in the map for (int i = 0; i < keys.length; i++) { assertEquals("indexOf with existing key failed", i, labRat.indexOf(keys[i])); } // test non existing key.. assertEquals("test with non-existing key failed", -1, labRat.indexOf("NonExistingKey")); } public void tearDown() throws Exception { labRat = null; } } libcommons-collections3-java.orig/src/test/org/apache/commons/collections/TestSetUtils.java0000644000175000017500000000713410777673435030657 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.Set; import junit.framework.Test; import org.apache.commons.collections.set.PredicatedSet; /** * Tests for SetUtils. * * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne * @author Neil O'Toole * @author Matthew Hawthorne */ 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)); } } libcommons-collections3-java.orig/src/test/org/apache/commons/collections/TestStaticBucketMap.java0000644000175000017500000000655010777673435032127 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; import java.util.Map; import junit.framework.Test; import org.apache.commons.collections.map.AbstractTestMap; /** * Unit tests. * {@link org.apache.commons.collections.StaticBucketMap}. * * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Michael A. Smith */ 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 }; } // Bugzilla 37567 public void test_get_nullMatchesIncorrectly() { StaticBucketMap map = new StaticBucketMap(17); map.put(null, "A"); assertEquals("A", map.get(null)); // loop so we find a string that is in the same bucket as the null for (int i = 'A'; i <= 'Z'; i++) { String str = String.valueOf((char) i); assertEquals("String: " + str, null, map.get(str)); } } public void test_containsKey_nullMatchesIncorrectly() { StaticBucketMap map = new StaticBucketMap(17); map.put(null, "A"); assertEquals(true, map.containsKey(null)); // loop so we find a string that is in the same bucket as the null for (int i = 'A'; i <= 'Z'; i++) { String str = String.valueOf((char) i); assertEquals("String: " + str, false, map.containsKey(str)); } } public void test_containsValue_nullMatchesIncorrectly() { StaticBucketMap map = new StaticBucketMap(17); map.put("A", null); assertEquals(true, map.containsValue(null)); // loop so we find a string that is in the same bucket as the null for (int i = 'A'; i <= 'Z'; i++) { String str = String.valueOf((char) i); assertEquals("String: " + str, false, map.containsValue(str)); } } } libcommons-collections3-java.orig/src/test/org/apache/commons/collections/TestTransformerUtils.java0000644000175000017500000004631610777673435032433 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import junit.framework.Test; import junit.framework.TestSuite; import junit.textui.TestRunner; import org.apache.commons.collections.functors.ConstantTransformer; import org.apache.commons.collections.functors.NOPTransformer; /** * Tests the org.apache.commons.collections.TransformerUtils class. * * @since Commons Collections 3.0 * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne * @author James Carman */ 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)); } } libcommons-collections3-java.orig/src/test/org/apache/commons/collections/TestTreeBag.java0000644000175000017500000000460610777673435030415 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.collections.bag.AbstractTestBag; /** * Extension of {@link TestBag} for exercising the {@link TreeBag} * implementation. * * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Chuck Burdick */ 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()); } } libcommons-collections3-java.orig/src/test/org/apache/commons/collections/TestTreeMap.java0000644000175000017500000000403310777673435030433 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; import java.util.TreeMap; import org.apache.commons.collections.map.AbstractTestMap; /** * Tests TreeMap. * * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Jason van Zyl */ 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"); } } libcommons-collections3-java.orig/src/test/org/apache/commons/collections/TestTypedCollection.java0000644000175000017500000000517510777673435032207 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; import java.util.ArrayList; import java.util.Collection; import java.util.List; /** * Tests TypedCollection. * * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Stephen Colebourne */ 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")); } } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootlibcommons-collections3-java.orig/src/test/org/apache/commons/collections/TestUnboundedFifoBuffer.javalibcommons-collections3-java.orig/src/test/org/apache/commons/collections/TestUnboundedFifoBuffer.ja0000644000175000017500000003223410777673435032434 0ustar godgod/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import junit.framework.Test; import org.apache.commons.collections.collection.AbstractTestCollection; /** * Test cases for UnboundedFifoBuffer. * * @version $Revision: 646780 $ $Date: 2008-04-10 13:48:07 +0100 (Thu, 10 Apr 2008) $ * * @author Unknown */ 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 void testInternalStateAdd() { UnboundedFifoBuffer test = new UnboundedFifoBuffer(2); assertEquals(3, test.m_buffer.length); assertEquals(0, test.m_head); assertEquals(0, test.m_tail); test.add("A"); assertEquals(3, test.m_buffer.length); assertEquals(0, test.m_head); assertEquals(1, test.m_tail); test.add("B"); assertEquals(3, test.m_buffer.length); assertEquals(0, test.m_head); assertEquals(2, test.m_tail); test.add("C"); // forces m_buffer increase assertEquals(5, test.m_buffer.length); assertEquals(0, test.m_head); assertEquals(3, test.m_tail); test.add("D"); assertEquals(5, test.m_buffer.length); assertEquals(0, test.m_head); assertEquals(4, test.m_tail); } public void testInternalStateAddWithWrap() { UnboundedFifoBuffer test = new UnboundedFifoBuffer(3); assertEquals(4, test.m_buffer.length); assertEquals(0, test.m_head); assertEquals(0, test.m_tail); test.add("A"); assertEquals(4, test.m_buffer.length); assertEquals(0, test.m_head); assertEquals(1, test.m_tail); test.add("B"); assertEquals(4, test.m_buffer.length); assertEquals(0, test.m_head); assertEquals(2, test.m_tail); test.add("C"); assertEquals(4, test.m_buffer.length); assertEquals(0, test.m_head); assertEquals(3, test.m_tail); test.remove("A"); assertEquals(4, test.m_buffer.length); assertEquals(1, test.m_head); assertEquals(3, test.m_tail); test.remove("B"); assertEquals(4, test.m_buffer.length); assertEquals(2, test.m_head); assertEquals(3, test.m_tail); test.add("D"); assertEquals(4, test.m_buffer.length); assertEquals(2, test.m_head); assertEquals(0, test.m_tail); test.add("E"); assertEquals(4, test.m_buffer.length); assertEquals(2, test.m_head); assertEquals(1, test.m_tail); } public void testInternalStateRemove1() { UnboundedFifoBuffer test = new UnboundedFifoBuffer(4); test.add("A"); test.add("B"); test.add("C"); assertEquals(5, test.m_buffer.length); assertEquals(0, test.m_head); assertEquals(3, test.m_tail); test.remove("A"); assertEquals(5, test.m_buffer.length); assertEquals(1, test.m_head); assertEquals(3, test.m_tail); test.add("D"); assertEquals(5, test.m_buffer.length); assertEquals(1, test.m_head); assertEquals(4, test.m_tail); } public void testInternalStateRemove2() { UnboundedFifoBuffer test = new UnboundedFifoBuffer(4); test.add("A"); test.add("B"); test.add("C"); assertEquals(5, test.m_buffer.length); assertEquals(0, test.m_head); assertEquals(3, test.m_tail); test.remove("B"); assertEquals(5, test.m_buffer.length); assertEquals(0, test.m_head); assertEquals(2, test.m_tail); test.add("D"); assertEquals(5, test.m_buffer.length); assertEquals(0, test.m_head); assertEquals(3, test.m_tail); } public void testInternalStateIteratorRemove1() { UnboundedFifoBuffer test = new UnboundedFifoBuffer(4); test.add("A"); test.add("B"); test.add("C"); assertEquals(5, test.m_buffer.length); assertEquals(0, test.m_head); assertEquals(3, test.m_tail); Iterator it = test.iterator(); it.next(); it.remove(); assertEquals(5, test.m_buffer.length); assertEquals(1, test.m_head); assertEquals(3, test.m_tail); test.add("D"); assertEquals(5, test.m_buffer.length); assertEquals(1, test.m_head); assertEquals(4, test.m_tail); } public void testInternalStateIteratorRemove2() { UnboundedFifoBuffer test = new UnboundedFifoBuffer(4); test.add("A"); test.add("B"); test.add("C"); Iterator it = test.iterator(); it.next(); it.next(); it.remove(); assertEquals(5, test.m_buffer.length); assertEquals(0, test.m_head); assertEquals(2, test.m_tail); test.add("D"); assertEquals(5, test.m_buffer.length); assertEquals(0, test.m_head); assertEquals(3, test.m_tail); } public void testInternalStateIteratorRemoveWithTailAtEnd1() { UnboundedFifoBuffer test = new UnboundedFifoBuffer(3); test.add("A"); test.add("B"); test.add("C"); test.remove("A"); test.add("D"); assertEquals(4, test.m_buffer.length); assertEquals(1, test.m_head); assertEquals(0, test.m_tail); Iterator it = test.iterator(); assertEquals("B", it.next()); it.remove(); assertEquals(4, test.m_buffer.length); assertEquals(2, test.m_head); assertEquals(0, test.m_tail); } public void testInternalStateIteratorRemoveWithTailAtEnd2() { UnboundedFifoBuffer test = new UnboundedFifoBuffer(3); test.add("A"); test.add("B"); test.add("C"); test.remove("A"); test.add("D"); assertEquals(4, test.m_buffer.length); assertEquals(1, test.m_head); assertEquals(0, test.m_tail); Iterator it = test.iterator(); assertEquals("B", it.next()); assertEquals("C", it.next()); it.remove(); assertEquals(4, test.m_buffer.length); assertEquals(1, test.m_head); assertEquals(3, test.m_tail); } public void testInternalStateIteratorRemoveWithTailAtEnd3() { UnboundedFifoBuffer test = new UnboundedFifoBuffer(3); test.add("A"); test.add("B"); test.add("C"); test.remove("A"); test.add("D"); assertEquals(4, test.m_buffer.length); assertEquals(1, test.m_head); assertEquals(0, test.m_tail); Iterator it = test.iterator(); assertEquals("B", it.next()); assertEquals("C", it.next()); assertEquals("D", it.next()); it.remove(); assertEquals(4, test.m_buffer.length); assertEquals(1, test.m_head); assertEquals(3, test.m_tail); } public void testInternalStateIteratorRemoveWithWrap1() { UnboundedFifoBuffer test = new UnboundedFifoBuffer(3); test.add("A"); test.add("B"); test.add("C"); test.remove("A"); test.remove("B"); test.add("D"); test.add("E"); assertEquals(4, test.m_buffer.length); assertEquals(2, test.m_head); assertEquals(1, test.m_tail); Iterator it = test.iterator(); assertEquals("C", it.next()); it.remove(); assertEquals(4, test.m_buffer.length); assertEquals(3, test.m_head); assertEquals(1, test.m_tail); } public void testInternalStateIteratorRemoveWithWrap2() { UnboundedFifoBuffer test = new UnboundedFifoBuffer(3); test.add("A"); test.add("B"); test.add("C"); test.remove("A"); test.remove("B"); test.add("D"); test.add("E"); assertEquals(4, test.m_buffer.length); assertEquals(2, test.m_head); assertEquals(1, test.m_tail); Iterator it = test.iterator(); assertEquals("C", it.next()); assertEquals("D", it.next()); it.remove(); assertEquals(4, test.m_buffer.length); assertEquals(2, test.m_head); assertEquals(0, test.m_tail); } public void testInternalStateIteratorRemoveWithWrap3() { UnboundedFifoBuffer test = new UnboundedFifoBuffer(3); test.add("A"); test.add("B"); test.add("C"); test.remove("A"); test.remove("B"); test.add("D"); test.add("E"); assertEquals(4, test.m_buffer.length); assertEquals(2, test.m_head); assertEquals(1, test.m_tail); Iterator it = test.iterator(); assertEquals("C", it.next()); assertEquals("D", it.next()); assertEquals("E", it.next()); it.remove(); assertEquals(4, test.m_buffer.length); assertEquals(2, test.m_head); assertEquals(0, test.m_tail); } } libcommons-collections3-java.orig/xdocs/0000755000175000017500000000000011010124151016703 5ustar godgodlibcommons-collections3-java.orig/xdocs/images/0000755000175000017500000000000011010124151020150 5ustar godgodlibcommons-collections3-java.orig/xdocs/images/logo.png0000644000175000017500000003276110777673303021662 0ustar godgodPNG  IHDR,dcbKGD pHYs  ~tIME "ns IDATx}{X~.珎'.`S0NI%@@/XcbYE3I4oǻ%)~s,AABDo\2c}[aY{Y{ޯ 2s\q$v.rQW']&]&]&]&]&]&]&]&]&]&]&]&݋akKiDoᷳkػ7od wv)//ĉyyy𸿿` `AoʲQpPHL&SfffxxxXXbb"'Jv9FҥKZZZP&%%ݺuڪ,99ٮ5(77ni7;v 5l˰'NHNNFͥfͲenݢ]fWClBBBBB11~˱n3g[___[[{Çغuk}}[L5c *>ҶmР?Ѹl2RZZZ]]]}}}RRG yf]]ݭ[[1Td]p}.-\Z j:u*2_h42aaa uuu555[l G̑#G V[[W_mٲn|Mcc#t}MM͑#GBCCQNmmm]]vrص/^qիW嗪Оظq7\lm߾eXbbb7oRi$%''9R Ϝ9듒Ҷl2uTwީںu+7!!!==}۶m7o2eNS3߼yq>rH56l`0| cի#F`}[nڴ)66.smm[~IdBBB]]͛7]V]]M}\p9r]î_~ԴiӶm۶u֩Srtڵk_1h;v પׯթt&r @^___ƍJ\;C{׷իQc,--UUUTdcbbkjjX֖ ڳgOuu5xb1LVbŝ?Auul.++;qℯ/e.--X,7nhllX`Ztx嗋^ :yQ_|Z6)//rʕ+9沲Z/F#"0>>͛jΰk֬0s.0v577s悦:u_~,//|r`` \rdާ!`0ԀfbTVVVUUUUU۷xʌFb~zCCC' 5xԔ炂 c(j4F֭[OիO> ( TThh;-N0GGGܹ/\C=#!hCpp|?O? :t,NVkkkkkkkϜ9J۷/22rڵ=ztMo H1?ѽ{ҥK'NأGƘ$I jdeea~UV=sVw|bf555\[[[VVQ裏^}=zAIIzVuȐ!ĦCCC@ChV u:/\0}tp V+45 >L>gϞh;F?r/ihhKٳg_'O3I@B\{544ѯ_ 2vZoŠ'z-*C(1x-:s̙O=L <iO?tcc#mb*eyٲe ߧ9}?-4 QXѸҬCG0T2??*2%!91NmD퀐ntt4v?E n۶m/^gϞtu+77fC ill.EÖ<==H}b]z}E*$Iݻw8p .ۭ[75ÇqC :hZٳ ְ|Ѳ|rdM M8}.b2\0ʖ̡|ڵ O-}777VYG?J0;;?ۗC;,C={~:Jpp0s( rtnu4bũݺuw1e MKEř10tww80B3NJ0P2ƞx XPÂm=<<+W`S7  dii@YpMIAɣGBdwssvb(:hık t)3 H@ gdooo@S* &v}G$ #`nrw_n<<`DsM$>]`ddupYC^^+BmێX,@qޮԆmKI$>%%%..c>}O<_tI=Q#!2% S Ni:\\Y&*rӁ@L]CmW& (H VgYl pK>,l;(iii'OVudȐ -w6滇uC8ѣmM8Q7O<}E\qZ Ha; 0l۾+_9zKN;kw;!c\p svү_?v;@ VQ]V\Ezo9rdl6'\ Aġ#Ջc"'++kԨQ4r.))AQ݅ @E"(]\QYYYYY)jAj؀//GNMMB?rʏ>۷ ;q^s-//Uv5jԧ~J]ٳg 6x`,wk')44&+fkۡCrl*ѼG'N iQk ۙr[)))eeeX?c@`xxxHH- 6= mr^x1N 1AMFꫯFd F__q Zݓ,YYY4=-! SLԶN@(Œ3#G3&//CԲeÍFczz:҂ഴ4*jΝf+ 98teS!t=RYY}vn7-2"5ݲ_RSSBV¾O>ٷo_Z)A8Zh'Œп9sdddddddff&''?pX)==ˋ6oLE8ZB U_(n۶8Y|yyy9An0Au`I_B`V\y:a_z9!I:3i&_+**֬Y3a„c>s˗/l۶-::O~+:pEPIIɬYh-(L^߻w< 22ܼ9=p Ree3vcFJ>xA &FFAy8q'rkk[?pbӧO2e fnmm{EEEڨFUUUgggsǩPȄG}SՎ3d2X={0t:]HH=_}I&MpV m<==xݦN}.]!弽"""0Va£ܘ0L*t?Þ:uテRь1`0t:XZJ$Q!Zc~x<ԩS zj, =.k0fΜ ̐\!3 d0pkbXj7oܽ{wwwqơX*1O:rww"Lיyڴi ¤-+++**:t \N躻\Oo޼[n+V~BdL2h ɓ'}||?¥REEEUUU%%%fNu >"oKK c AKoF uwaыJC~8s(:P]__T6wjL ,IFf |$&$aelO28f0X02p!2Sɨo tI<==AOaC`LE*hjBsИt5)vhЗ:뙦E!(Gᘹy+R)(E 5Om t"( O19+KA  q02%z@(B]`bE#nK %DBx& KBT8 JPhWOӠ'= =S9J jR$G{;ЩP` X";;a-,, ijUޥwqx:233?Ao" Vuڴiǎ۹s'=(ܚٯ5d2|IAfϞcq{i z|%5P`` ѷ51^-3`ʃsK22%''C`jjjjjd~ r^!D w>^M_UÆ Xefw$Z}KwGhhm] ]Ƃ#7"qqq&2-W}x,8hEރ !mOZbw\ln!LpHmvik$K2wN:l ^g$ٳTWE|rN_; ˾8 tB~HAAAih*Ld\g[ Җ⢮`Kw3eNY,& /ILLt[z9x \AK'K𡠠(V +1,S+PuЮ0^o˗sWԔeggø'؞TwG3jA9>}d2L&D}d2egg߮AgA`oVӡ>?cGXXرcDYYY.xѣM&V5Q5XXv,˲|ĉp0DZҥK`x_o;\C_t)pΚ5 ojj—p /%d̙)ʕ+.\8w\IIɹs.\p劊 .^ߟ={ٳ?åK˫kjjbO?Qg͚;ⴲZW\5kcɒ%!/Qǎ۱cǎ;Qϸׯ[n͚5999/_6111pآEn޼yk׮]zڵk7nܨ{khɒ%koFz[ŋq1T__44NFF$&&M~gux{p~),䫯K._U;wG1$@777#OHHHEEEii?xܹg~?SYYb:u*SXXX={s~˗/k׮]x]۾};ʩA,^gxCC*<}t4 ťK.\?^p.++3G~U]vZe -@ϤӧOOKK<Çqƍ7n޼ ǀJKK& jBp?(5j sxrYYY=0;v1b}> wrIDATrrrrh50F0`l(tBå4sx2O4PNZeff1cFcBBŽ;lT-+"X4 mۭ?K'팃Opp/^ZBLw Ik„ 1^xb|E[lpsrrÆ k}5\$Ii?88^Qhdh>Sۙ U쌄o??777 AAA֭.,++C!QQQ7oKFTTSDR . e˖z}JJ g dY~wc^^^Vrjyy9z`:u*M3l2PQV+]aذap'Zٽ{76=_E m0^}U./T`c-Hո8p\Y#ŠlF0f{%mDž L&󫯾Vi];ch4Xi/Kb V#ׯ V\jFh0 ,3'uUͅ0ƒYɈAnҶlقΊKjs@IӧOXXxdm۶ ޽{͚55k<ݤ7_CCC$U 6@@#З_~ʒr{7}Ȑ!ȳuV._?93~AA%::?/,,hjjȖIaa!j޳gOPklqqq>9XAAyz-+3''jTAVTEA(2"^~@$rڑf֭:u*[%u5YWPMp6H'!!!~x`{wQڴiӼLwށbtիWC)8xɆ *** $-02'MNz2%!`+)F΍7:hvVxMHFFLPnX-**GDD*[|H^Vkppphh( \n  2O#ÞRSa^^nB1GJq"n#磴ixI+c,22[W]Bո bYv-J3AVuڵ6l0͌I&[@Ԇ Y52# #Qxo+jÿ6 ~Ū\'-IREE3 ˈU 7::zʔ)s}q> }Ms\+%Iڼy?ӦM믽Pԑ +Pe|E&S {FbeY޻w/>>`pVʊ;\ܟhjBH+K!וڵk 'FGG"0N ~@)clذa4Udx[`AAu7hE[^v hl*VXX3~x\dYmX___ooot7o~{.--F-m~sW!-O 7vK~6gUݠƂ!AjsӑPx<5q~|||lؿ?>KBLbhN 7q_oFNN@# cJ^MAvfsFFZag}G0+7bpX,)))p:lqBQ=$v9ʲLחuf>/:|,Igi~oa:j6qjl޺(7!zcl6;Y[[[*t]Y@\±Q=w91UJFSTTXFtPƄ g i|ypdJ;t9:db@ ^|E>\\\ 3m|{,RWܬZm19 p2`߂.32Y,:-CÅDdBv' hU]Ӧ^ND8QWqU}g FͮK 3-H!;x z'00Iw}OVGj B0>А/>7my([~=N-Ps= ,;.\Bb8+qI~uQԪXttl{lx ngsdd}M 6m~~~&MBGZ.BjF\]44qȻ(Vo6m 8FGG#-˸qtcǎT'9\"f?xgiYn|@@mXe̙3x 8-rĥyڙ晑\!`())ݻL3yd:>Y] ` Z/_R?"رcWXANoȖI!E tϼy-[}II Z'IK.]#!$Iv{::ׯ_ Z{h~ZPKeY6)))qS810T굨v,b722َ0oHxAO%VjRFeU1XŌ-RZ knܸ[`J$-z>12!F!oݺ5..04 /~ר|Ԗ$i,c=#@3f̰;>oٲ%>>~7nąJÇSpMCy7wl3 8Dcccnjc+4@ž{Z}6Kl1#(^,\,vEM`06S, l3v d (CQ%fhBEHB@Bf[VW$cב_"e%(BxMPۣn4M͘QEQt:pÊlXjw w۸B8_0^L+LGdCf;g%UEP j=Sk8b tFe)@6D1c]@YWBc@ڈ\cJ=d̡?JLTNR^_Wh(89%Lq2LSqfAԈE5héz_n@ж\f ?5ۈ)sIV]W'sП85*@0pn9.2?9Ȭ椒Wv*1*ܒ,+ jI#ǹVsuAl 4]r8!GgmdA@ȈpZq]_8h'Yma'l(9XT3m5ߕAd캚qvЮh ?8 NK4Nvî>gB j.?;~.C@vmkSY;`vFNj~2Bé'trE.`rE.`rE.`rE.`rE.`rE.`2!IENDB`libcommons-collections3-java.orig/xdocs/style/0000755000175000017500000000000011010124151020043 5ustar godgodlibcommons-collections3-java.orig/xdocs/style/project.css0000644000175000017500000000010310777673274022257 0ustar godgod@import url("http://commons.apache.org/style/commons-maven.css"); libcommons-collections3-java.orig/xdocs/building.xml0000644000175000017500000000720510777673304021262 0ustar godgod Building Commons Documentation Team

              Commons Collections uses Ant as its primary build system, however Maven is used for site generation.

              You may also be interested in the v3.2.1 release notes.

              To build a jar file, change into Collection's root directory and run "ant jar". The result will be in the "build" subdirectory.

              All tests can be run with "ant test". A single test can be run with "ant -Dtestcase=org.apache.commons.collections.TestXxx test".

              To build the Javadocs, run "ant javadoc". The result will be in "build/docs/apidocs".

              The following Maven 2 commands can be used to build collections:

              • mvn clean - clean up
              • mvn test - compile and run the unit tests
              • mvn site - create io documentation
              • mvn package - build the jar
              • mvn install - build the jar and install in local maven repository
              • mvn site assembly:assembly - Create the source and binary distributions

              The following Maven 1 commands can be used to build collections:

              • maven clean - clean up
              • maven test - compile and run the unit tests
              • maven site - create io documentation
              • maven jar - build the jar
              • maven dist - Create the source and binary distributions

              The following Ant commands can be used to build collections:

              • ant clean - clean up
              • ant test - compile and run the unit tests
              • ant javadoc - create javadocs
              • ant jar - build the jar
              • ant dist - Create the source and binary distributions
              libcommons-collections3-java.orig/xdocs/compatibility.xml0000644000175000017500000000764110777673304022342 0ustar godgod Compatibility Commons Documentation Team

              This page details the compatibility of different collections releases.

              There are two types of compatibility discussed here, source and binary.

              • Two versions are source compatible when application code can be compiled against either version successfully. The compilation may result in deprecation warnings but that is perfectly acceptable. When code is source incompatible, it fails to compile, thus this type of incompatibility is easy to find.
              • Two versions are binary compatible when application code compiled against one version will run using the other version without recompilation. This is much more difficult to test for, and follows quite complicated rules from the Java language.

              Releases of commons collections aim to be source and binary compatible within minor versions, and to avoid breakages as much as possible between major versions.

              Commons collections 3.0 is source compatible with version 2.1 and 2.0 with the exception of classes previously deprecated in 2.0/2.1 (which were removed in 3.0).

              Commons collections 3.0 is binary compatible with version 2.1 and 2.0 except for certain methods on one class. As the release was a major version, this is permitted, however it was unintentional and an error. The problem is in the IteratorUtils class (see methods below). (Strictly speaking, there are some minor incompatibilities on other classes, but these changes were deliberate and have not caused any known issues.)

              It is not possible to make v2.1 and v3.0 compatible without futher binary incompatibility. The chosen solution is to provide a work around by releasing v2.1.1 and v3.1. The following deprecations must be resolved in v2.1.1 to allow compatibiilty with v3.1.

              • Deprecated IteratorUtils.arrayIterator(...) - use new ArrayIterator(...) instead
              • Deprecated IteratorUtils.singletonIterator(...) - use new SingletonIterator(...) instead
              • Deprecated IteratorUtils.emptyIterator() - use EmptyIterator.INSTANCE instead
              • Deprecated IteratorUtils.emptyListIterator() - use EmptyListIterator.INSTANCE instead
              • Deprecated IteratorUtils.EMPTY_ITERATOR - use EmptyIterator.INSTANCE instead
              • Deprecated IteratorUtils.EMPTY_LIST_ITERATOR - use EmptyIterator.INSTANCE instead

              For the future, a new tool clirr is being developed to help spot binary incompatibility before release.

              libcommons-collections3-java.orig/xdocs/cvs-usage.xml0000644000175000017500000000330210777673304021354 0ustar godgod Source repository Commons Documentation Team

              Apache Commons Collections is hosted on the Apache subversion repository.

              The project URL is:
              http://svn.apache.org/repos/asf/commons/proper/collections/trunk

              The best way to view the repository is via the subversion viewer.

              The alternative is to use the native subversion display.

              libcommons-collections3-java.orig/xdocs/download_collections.xml0000644000175000017500000001723310777673304023674 0ustar godgod Download Commons Collections Commons Documentation Team

              We recommend you use a mirror to download our release builds, but you must verify the integrity of the downloaded files using signatures downloaded from our main distribution directories. Recent releases (48 hours) may not yet be available from the mirrors.

              You are currently using [preferred]. If you encounter a problem with this mirror, please select another mirror. If all mirrors are failing, there are backup mirrors (at the end of the mirrors list) that should be available.

              [if-any logo][end]

              Other mirrors:

              The KEYS link links to the code signing keys used to sign the product. The PGP link downloads the OpenPGP compatible signature from our main site. The MD5 link downloads the checksum from the main site.

              For more information concerning Commons Collections, see the Commons Collections web site.

              libcommons-collections3-java.orig/xdocs/history.xml0000644000175000017500000001043610777673304021166 0ustar godgod History Commons Documentation Team

              Commons-Collections is a classic example of an open-source project evolving over time. This page documents some of the key stages.

              Collections 1.0 was a gathering of different Collection, Comparator, Iterator and Utility classes written elsewhere in Jakarta. At this stage, the component focussed mainly on getting re-use of code by making everything available together.

              All classes were placed in one package except the comparators, which had their own subpackage.

              Collections 2.0 started the process of growth. The Bag interface was added with various implementations. Also added were additional collections implementations.

              All classes were placed in one package except the comparators, which had their own subpackage.

              Collections 2.1 increased the growth again. The Buffer interface was added, unifying various previous implementations. Numerous decorators were added as inner classes that behave like the unmodifiable or synchronized JDK decorators.

              As the size of the component increased, the iterators were broken out into their own subpackage. Thus there were now three packages, main, comparator and iterator.

              Collections 3.0 represented a re-birth of collections after an 18 month absence. Many, many classes were added to CVS but not released including primitive and event-generating classes. In order to control the size of the collections distribution, these became two new projects - primitives and events.

              New interfaces BidiMap, MapIterator, ResettableIterator and KeyValue were added. Also added were many new implementations of existing collections, especially Maps.

              As more decorators were added the decision was taken to create a new subpackage for the decorators (no more inner classes). However, it became clear that whether a class was a decorator or not was not the most important division in finding a collection. As a result of this, and the general ongoing growth in the component, a full subpackage layout was chosen - one subpackage for each principal collections interface.

              Essentially the 3.0 release represented the result of changing from a 'dumping ground' of re-used collections to a component designed for the purpose. Of course, backwards compatibility has been retained during all transitions using deprecation.

              Collections 2.1.1 was a patch release to v2.1. Unfortunately, v3.0 created a binary incompatibility in the IteratorUtils class. This patch was created as a work around, enabling v2.1.1 to be compatible with v3.1.

              Collections 3.1 fixed some bugs in v3.0 and adds a few new enhancements. The most notable change is a new list implementation, TreeList, that is well balanced for insertions and removals at any index. Other changes included more classes implementing Serializable and a ReferenceIdentityMap.

              Collections 3.2 combined bug fixes and some new features. Notably MultiValueMap is a new more flexible implementation of MultiHashMap.

              Collections 3.2.1 Re-packaged v3.2 release which is OSGi enabled.

              libcommons-collections3-java.orig/xdocs/index.xml0000644000175000017500000001110110777673304020562 0ustar godgod Home Commons Documentation Team

              The Java Collections Framework was a major addition in JDK 1.2. It added many powerful data structures that accelerate development of most significant Java applications. Since that time it has become the recognised standard for collection handling in Java.

              Commons-Collections seek to build upon the JDK classes by providing new interfaces, implementations and utilities. There are many features, including:

              • Bag interface for collections that have a number of copies of each object
              • Buffer interface for collections that have a well defined removal order, like FIFOs
              • BidiMap interface for maps that can be looked up from value to key as well and key to value
              • MapIterator interface to provide simple and quick iteration over maps
              • Type checking decorators to ensure that only instances of a certain type can be added
              • Transforming decorators that alter each object as it is added to the collection
              • Composite collections that make multiple collections look like one
              • Ordered maps and sets that retain the order elements are added in, including an LRU based map
              • Identity map that compares objects based on their identity (==) instead of the equals method
              • Reference map that allows keys and/or values to be garbage collected under close control
              • Many comparator implementations
              • Many iterator implementations
              • Adapter classes from array and enumerations to collections
              • Utilities to test or create typical set-theory properties of collections such as union, intersection, and closure

              A getting started User's Guide is available as are various project reports.

              The JavaDoc API documents are available online:

              The subversion repository can be browsed.

              The latest version is v3.2.1 - Download now!
              The release notes are also available.

              For previous releases, see the Apache Archive

              The commons mailing lists act as the main support forum. The user list is suitable for most library usage queries. The dev list is intended for the development discussion. Please remember that the lists are shared between all commons components, so prefix your email by [collections].

              Issues may be reported via ASF JIRA. Please read the instructions carefully to submit a useful bug report or enhancement request.

              libcommons-collections3-java.orig/xdocs/issue-tracking.xml0000644000175000017500000001347510777673304022423 0ustar godgod Commons Collections Issue tracking Commons Documentation Team

              Commons Collections uses ASF JIRA for tracking issues. See the Commons Collections JIRA project page.

              To use JIRA you may need to create an account (if you have previously created/updated Commons issues using Bugzilla an account will have been automatically created and you can use the Forgot Password page to get a new password).

              If you would like to report a bug, or raise an enhancement request with Commons Collections please do the following:

              1. Search existing open bugs. If you find your issue listed then please add a comment with your details.
              2. Search the mailing list archive(s). You may find your issue or idea has already been discussed.
              3. Decide if your issue is a bug or an enhancement.
              4. Submit either a bug report or enhancement request.

              Please also remember these points:

              • the more information you provide, the better we can help you
              • test cases are vital, particularly for any proposed enhancements
              • the developers of Commons Collections are all unpaid volunteers

              For more information on subversion and creating patches see the Apache Contributors Guide.

              You may also find these links useful:

              libcommons-collections3-java.orig/xdocs/navigation.xml0000644000175000017500000000400610777673304021620 0ustar godgod Commons Collections &commons; libcommons-collections3-java.orig/xdocs/pick.xml0000644000175000017500000003154110777673304020413 0ustar godgod Choosing a collection Commons Documentation Team

              Commons-Collections and the Java Collections Framework provide a wide variety of collections to choose from. This choice can be bewildering, so this document seeks to help you choose.

              Collection or Map

              Do you want to store a map of key-value pairs? Then use a Map. For example you could decode country codes, where 'FR' maps to 'France' and 'GB' maps to 'United Kingdom'.
              Or do you want to store a simple collection of elements? Then use a Collection. For example you could store types of tree, 'Oak', 'Pine' and 'Birch'.

              libcommons-collections3-java.orig/xdocs/proposal.xml0000644000175000017500000000767210777673304021334 0ustar godgod Proposal

              The Java Collections Framework provides a set of abstract data type interfaces and implementations that offer both a wealth of useful functionality, and a solid foundation for extending that functionality.

              Many Jakarta projects have needs or design criteria that extend beyond the core Collections API, such as introducing new abstract data types (e.g., Avalon's BinaryHeap) or changing the behaviour of existing abstract data types (e.g., Struts' FastHashMap).

              In keeping with the spirit of the Collections API and of abstract data types in general, these components can and should be shared assets. A Commons package for abstract data types would encourage the development and reuse of a robust set of collections classes.

              The package will create and maintain a set of collections and related classes designed to be compatible with the Java Collections Framework, and to be distributed under the ASF license.

              Collections relies only on standard JDK 1.2 (or later) APIs for production deployment. It utilizes the JUnit unit testing framework for developing and executing unit tests, but this is of interest only to developers of the component. Collections will also be a dependency for several future proposed components for the Apache Commons subproject.

              No external configuration files are utilized.

              The initial codebase was harvested from existing and proposed Jakarta packages, including the Commons Database Connection Pool, Struts, and Avalon.

              The proposed package name for the new component is org.apache.commons.collections.

              • CVS Repository - New directory collections in the jakarta-commons CVS repository. All initial committers are already committers on jakarta-commons, so no additional user setups are required.
              • Mailing List - Discussions will take place on the general jakarta-commons@jakarta.apache.org mailing list. To help list subscribers identify messages of interest, it is suggested that the message subject of messages about this component be prefixed with [Collections].
              • Bugzilla - New component "Collections" under the "Commons" product category, with appropriate version identifiers as needed.
              • Jyve FAQ - New category "commons-collections" (when available).
              • Peter Donald
              • Craig McClanahan
              • Rodney Waldhoff
              • James Strachan
              libcommons-collections3-java.orig/xdocs/release_3_2.xml0000644000175000017500000002034210777673304021545 0ustar godgod Release notes for v3.2 Commons Documentation Team

              These are the release notes for Commons Collections v3.2:


              Commons collections is a project to develop and maintain collection classes based on and inspired by the JDK collection framework. This project is JDK1.2 compatible, and does not use JDK1.5 generics.

              This release adds various new classes and fixes a number of bugs. All feedback should be directed to commons-user at jakarta.apache.org.


              COMPATIBILITY

              This release is fully source and binary compatible with v3.1. (Checks performed using JDiff and Clirr, thanks). Please check the bug fixes to ensure you weren't relying on the behaviour of a bug.

              There are two new deprecations:
              BeanMap is now deprecated and will be removed in v4.0. The class is now available in commons-beanutils (full jar version). This change was made to ensure that all bean related collections were in one place (ie. beanutils). If this causes major headaches to anyone please contact commons-dev at jakarta.apache.org.

              MultiHashMap is now deprecated and will be removed in v4.0. The class is now available as MultiValueMap in the map subpackage. This new version of the class is a decorator and can wrap maps other than HashMap making it much more flexible. If this causes major headaches to anyone please contact commons-dev at jakarta.apache.org.

              NEW CLASSES

              • MultiValueMap - Decorator implementation of MultiMap providing control over the map and collection implementations, updated MapUtils to match [29440]
              • DefaultedMap - Returns a default value when the key is not found, without adding the default value to the map itself [30911]
              • GrowthList - Decorator that causes set and indexed add to expand the list rather than throw IndexOutOfBoundsException [34171]
              • LoopingListIterator - When the end of the list is reached the iteration continues from the start, updated IteratorUtils to match [30166]
              • ReverseListIterator - A list iterator that returns the elements from the list in reverse order [39224]
              • BoundedBuffer - A new wrapper class which can make any buffer bounded, updated BufferUtils to match [37473]

              ENHANCEMENTS

              • CollectionUtils.addIgnoreNull - Adds to the collection if the value being added is not null [30020]
              • MapUtils.putAll - Puts an array of key/value pairs into a map [30882]
              • CollectionUtils/MapUtils.isEmpty/isNotEmpty - Null-safe checks of collection emptyness [35890]
              • CollectionUtils.sizeIsEmpty - Checks if a collection, array, map, iterator or enumeration is empty
              • CollectionUtils/ListUtils - retainAll/removeAll that don't change original colllection
              • ExtendedProperties - Accepts List elements (does not enforce Vector) as values [36812]
              • ExtendedProperties - new Methods getList(String key) and getList(String key, List defaults) [36812]
              • ExtendedProperties - No longer uses an exception in normal processing [30497]
              • BlockingBuffer - now includes stack trace if InterupttedException occurs [33700]
              • BlockingBuffer - new methods that allow get and remove with a timeout, updated BufferUtils to match [27691]
              • BlockingBuffer - now allows you to specify a default timeout value for get/remove operations [37607]
              • TransformedMap/TransformedSortedMap - new factory decorateTransform() that transforms any existing entries in the map [30959]
              • ListOrderedMap - values can now be accessed as a List using valueList() [37015]
              • ListOrderedMap - additional list-like method, setValue(int,Object)
              • ListOrderedMap - additional method, put(int,Object,Object)
              • PriorityBuffer - now Serializable [36163]
              • ListIteratorWrapper - now implements ResettableListIterator [39449]
              • IfClosure - add single argument constructor, updated CllosureUtils to match [38495]
              • All/Any/One/None Predicate - allow construction with zero or one predicates [37979]

              BUG FIXES

              • FastArrayList - Fix iterators and views to work better in multithreaded environments
              • FastArrayList - Fix iterator remove where ConcurrentModificationException not as expected [34690]
              • CursorableLinkedList (list subpackage) - Fix iterator remove/set not throwing IllegalStateException after next-previous-removeByIndex [35766]
              • TreeList/CursorableLinkedList/NodeCachingLinkedList/AbstractLinkedList - Fix iterator remove not working properly when called after previous [35258]
              • TreeList - remove(int) could break class invariants, breaking iterator previous [35258]
              • SetUniqueList.set(int,Object) - Destroyed set status in certain circumstances [33294]
              • AbstractLinkedMap.init() - Now calls createEntry() to create the map entry object [33706]
              • AbstractHashedMap deserialization - Fix to prevent doubling of internal data array [34265]
              • AbstractHashedMap initialization - Fix to setup threshold correctly, improving performance [35012]
              • BeanMap.initialize() - Internal variable now correctly initialised with only write methods that actually exist [15895]
              • MultiHashMap.remove(key, item) - Was returning the item even when nothing was removed [32366]
              • MultiHashMap.putAll(multimap) - Was adding the collection as a single item rather than individually [35631]
              • MultiHashMap - Enable compilation using J#
              • Flat3Map.equals() - Fix to make flat mode comparison actually work [34917]
              • TransformedMap.putAll - Now allows putAll of an empty map [34686]
              • StaticBucketMap.containsKey - Fix incorrect null checking [37567]
              • AbstractMapBag.BagIterator.remove - Removing the last entry used to break the class invariants [35747]
              • BoundedFifoBuffer/CircularFifoBuffer - Fix serialization to work in case where buffer serialized when full [31433]
              • BoundedFifoBuffer - Fix iterator remove bug causing ArrayIndexOutOfBounds error [33071]
              • UnboundedFifoBuffer - Fix iterator remove bug causing ArrayIndexOutOfBounds error [35733]
              • UnboundedFifoBuffer - Fix deserialization to work with subsequant object manipulation [35763]
              • BlockingBuffer - Fix internal locking code (internal fix, no effect on users of BlockingBuffer) [37028]
              • IteratorChain.remove() - Fix to avoid IllegalStateException when one of the underlying iterators is a FilterIterator [34267]
              • FilterIterator - Correctly handle setting of iterator and predicate after object creation [38074]
              • ExtendedProperties.convertProperties() - Fix to handle default properties maps correctly [32204]
              • Add casts to avoid some JDK1.5 compilation warnings [35474]
              • Make serialization version ids private [37106]

              JAVADOC

              • MapUtils.safeAddToMap - Better comment
              • MapUtils.transformed*Map - Better comment
              • ListOrderedSet.decorate(List) - Better comment [32073]
              • BlockingBuffer - Add comments
              • Maps - synchronization comments [32573]
              • SwitchTransformer - defaultTransformer comment fix [39207]
              libcommons-collections3-java.orig/xdocs/release_3_2_1.xml0000644000175000017500000000325410777673304021770 0ustar godgod Release notes for v3.2.1 Commons Documentation Team

              These are the release notes for Commons Collections v3.2.1:


              Commons collections is a project to develop and maintain collection classes based on and inspired by the JDK collection framework. This project is JDK1.2 compatible, and does not use JDK1.5 generics.

              This v3.2.1 release is simply a re-packaging of the v3.2 release, with appropriate OSGi meta data added to the jar's manifest file.


              COMPATIBILITY

              This release is fully source and binary compatible with v3.2. For changes since the v3.1 see the v3.2 Release Notes.

              libcommons-collections3-java.orig/xdocs/tasks.xml0000644000175000017500000000260610777673304020612 0ustar godgod Tasks outstanding Commons Documentation Team

              The following ideas are on the TODO list, but please contact the mailing list before starting work:

              • Synchronized BidiMap decorators
              • IdentitySet
              • BidiMapUtils

              Would you like to Volunteer? If so, please contact the mailing lists.

              libcommons-collections3-java.orig/xdocs/userguide.xml0000644000175000017500000001456510777673304021470 0ustar godgod User guide Commons Documentation Team

              Commons-Collections provides a large number of classes to aid day to day programming. This document highlights some key features to get you started.

              Commons-collections uses a design approach to synchronization similar to the standard Java collections. The majority of the various implementations of collections, maps and bags are not thread safe without additional synchronization. The appropriate synchronizeXXX method on Collections is one way that these implementations can be synchronized for use in a multithreaded application.

              The class level javadocs should indicate whether a particular implementation is safe for multithreaded access without additional synchronization. Where there is no expicit indication that the implementation is thread safe then it should be assumed that synchronization is required. Please report the missing documentation to the commons development team.

              A Utility class is provided for each major collection interface. Thus, the Set and SortedSet interfaces are provided for by SetUtils. These classes provide useful methods for working with that collection type.

              The most methods are found on the two 'root' collection utility classes - CollectionUtils and MapUtils. As all other collection interfaces extend Collection or Map these utilities can be used widely. They include intersection, counting, iteration, functor and typecasting operations amongst others. The utility classes also provide access to collection decorator classes in a way similar to the JDK Collections class.

              The JDK Map interface always suffered from being difficult to iterate over. API users are forced to either iterate over an EntrySet or over the KeySet. Commons-Collections now provides a new interface - MapIterator that allows simple iteration over maps.

              IterableMap map = new HashedMap(); MapIterator it = map.mapIterator(); while (it.hasNext()) { Object key = it.next(); Object value = it.getValue(); it.setValue(newValue); }

              A new interface is provided for maps that have an order but are not sorted - OrderedMap. Two implementations are provided - LinkedMap and ListOrderedMap (a decorator). This interface supports the map iterator, and also allows iteration both forwards and backwards through the map.

              OrderedMap map = new LinkedMap(); map.put("FIVE", "5"); map.put("SIX", "6"); map.put("SEVEN", "7"); map.firstKey(); // returns "FIVE" map.nextKey("FIVE"); // returns "SIX" map.nextKey("SIX"); // returns "SEVEN"

              A new interface hierarchy has been added to support bidirectional maps - BidiMap. These represent maps where the key can lookup the value and the value can lookup the key with equal ease.

              BidiMap bidi = new TreeBidiMap(); bidi.put("SIX", "6"); bidi.get("SIX"); // returns "6" bidi.getKey("6"); // returns "SIX" bidi.removeValue("6"); // removes the mapping BidiMap inverse = bidi.inverseBidiMap(); // returns a map with keys and values swapped

              Additional interfaces are provided for ordered and sorted bidirectional maps. Implementations are provided for each bidirectional map type.

              A new interface hierarchy has been added to support queues and buffers - Buffer. These represent collections that have a well defined removal order.

              Buffer buffer = new UnboundedFifoBuffer(); buffer.add("ONE"); buffer.add("TWO"); buffer.add("THREE"); buffer.remove(); // removes and returns the next in order, "ONE" as this is a FIFO buffer.remove(); // removes and returns the next in order, "TWO" as this is a FIFO

              Implementations are provided for FIFO (queue), LIFO (stack) and Priority (removal in comparator order).

              A new interface hierarchy has been added to support bags - Bag. These represent collections where a certain number of copies of each element is held.

              Bag bag = new HashBag(); bag.add("ONE", 6); // add 6 copies of "ONE" bag.remove("ONE", 2); // removes 2 copies of "ONE" bag.getCount("ONE"); // returns 4, the number of copies in the bag (6 - 2)

              Implementations are provided for both unsorted and sorted Bags.

              libcommons-collections3-java.orig/build-testframework.xml0000644000175000017500000000622110777673551022340 0ustar godgod libcommons-collections3-java.orig/build.xml0000644000175000017500000006550610777673551017460 0ustar godgod libcommons-collections3-java.orig/checkstyle.xml0000644000175000017500000000322610777673551020506 0ustar godgod libcommons-collections3-java.orig/DEVELOPERS-GUIDE.html0000644000175000017500000001230710777673551021017 0ustar godgod Developers guide for Apache Commons "Collections" Package

              The Apache Commons Collections Package

              Developers Guide

              $Id: DEVELOPERS-GUIDE.html 646782 2008-04-10 12:58:57Z niallp $
              [Introduction] [Collection Interfaces] [Collection Implementations] [Utility Classes] [Coding Standards]

              1. INTRODUCTION

              The Collections package contains a set of Java classes that extend or augment the Java Collections Framework. This developers guide seeks to set out rules for the naming of classes and methods within the package. The purpose of this, as with all naming standards, is to improve the coherency and consistency of the whole API.

              The philosophy of the naming standards is to follow those of java.util.Collections.

              2. COLLECTION INTERFACES

              Collection interfaces are new types of collections not included in Java. Examples include Bag and SortedBag. These interfaces shall:

              • be top level interfaces
              • have a name that describes their purpose

              3. COLLECTION IMPLEMENTATIONS

              Collection implementation are new implementations of collection interfaces. Examples include DoubleOrderedMap and DefaultMapBag. These interfaces shall:

              • be top level classes
              • have a name that ends with the collection type being implemented
              • have a name that describes their implementation
              • contain no public inner classes
              • only contain the collection implementation, and any methods specific to that implementation

              4. UTILITY CLASSES

              Utility classes provide additional functionality around an interface and its basic implementations. Examples include CollectionUtils and ListUtils.

              Each class shall follow the naming pattern XxxUtils where Xxx relates to the object being returned by the class, for example ListUtils and BagUtils. Variations on a theme (SortedBag as opposed to Bag) will be dealt with in one Utils class. Each Utils class shall:

              • be a single, static method based, class
              • have a name consisting of the interface name plus 'Utils'
              • deal with one collection interface and its variations
              • provide methods that decorate the interface with additional functionality
              • provide methods that perform useful utility functions on that interface

              Where the method in a Utils class is a decorator, the name shall consist of an adjective followed by the collection type. Typically such adjective is formed by appending an -ed suffix (meaning "having"/"characterized by") to the word describing the type of decorator. For example, synchronizedMap(Map) or predicatedSet(Set). Occasionally, such construct is awkward and a more suitable adjective can be used instead. For example, lazyList, unmodifiableList.

              These decorators should be implemented either as non-public, static, inner classes, or as public classes in a subpackage. If a subpackage is used, the constructors should be protected and a public static decorate() method provided on each class for construction.

              5. CODING STANDARDS

              Commons Collections follows similar style rules to many other Java open source projects, and the Sun conventions. Some specific conventions are:

              • No tabs, 4 space indentations
              • Curly brackets open at line end
              • Else, catch and finally statements after the closing bracket
              • Single space after keyword such as if
              • Two spaces between parameter name and description in @param
              • Generally copy the style of the surounding code

              And rememeber, the commons-dev mailing list is there for any discussions or queries about patches or new additions to collections.

              libcommons-collections3-java.orig/LICENSE.txt0000644000175000017500000002645010777673551017455 0ustar godgod 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. libcommons-collections3-java.orig/maven.xml0000644000175000017500000001345210777673551017460 0ustar godgod libcommons-collections3-java.orig/NOTICE.txt0000644000175000017500000000027110777673551017345 0ustar godgodApache Commons Collections Copyright 2001-2008 The Apache Software Foundation This product includes software developed by The Apache Software Foundation (http://www.apache.org/). libcommons-collections3-java.orig/pom.xml0000644000175000017500000003033110777673551017140 0ustar godgod org.apache.commons commons-parent 9 4.0.0 commons-collections commons-collections 3.2.1 Commons Collections 2001 Types that extend and augment the Java Collections Framework. http://commons.apache.org/collections/ jira http://issues.apache.org/jira/browse/COLLECTIONS scm:svn:http://svn.apache.org/repos/asf/commons/proper/collections/trunk scm:svn:https://svn.apache.org/repos/asf/commons/proper/collections/trunk http://svn.apache.org/viewvc/commons/proper/collections/trunk Stephen Colebourne scolebourne Morgan Delagrange morgand Matthew Hawthorne matth Geir Magnusson geirm Craig McClanahan craigmcc Phil Steitz psteitz Arun M. Thomas amamment Rodney Waldhoff rwaldhoff Henri Yandell bayard James Carman jcarman Robert Burrell Donkin rdonkin Rafael U. C. Afonso Max Rydahl Andersen Federico Barbieri Arron Bates Nicola Ken Barozzi Sebastian Bazley Matt Benson Ola Berg Christopher Berry Nathan Beyer Janek Bogucki Chuck Burdick Dave Bryson Julien Buret Jonathan Carlson Ram Chidambaram Steve Clark Eric Crampton Dimiter Dimitrov Peter Donald Steve Downey Rich Dougherty Tom Dunham Stefano Fornari Andrew Freeman Gerhard Froehlich Paul Jack Eric Johnson Kent Johnson Marc Johnson Nissim Karpenstein Shinobu Kawai Mohan Kishore Simon Kitching Thomas Knych Serge Knystautas Peter KoBek Jordan Krey Olaf Krische Guilhem Lavaux Paul Legato David Leppik Berin Loritsch Hendrik Maryns Stefano Mazzocchi Brian McCallister Steven Melzer Leon Messerschmidt Mauricio S. Moura Kasper Nielsen Stanislaw Osinski Alban Peignier Mike Pettypiece Steve Phelps Ilkka Priha Jonas Van Poucke Will Pugh Herve Quiroz Daniel Rall Robert Ribnitz Huw Roberts Henning P. Schmiedehausen Howard Lewis Ship Joe Raysa Thomas Schapitz Jon Schewe Andreas Schlosser Christian Siefkes Michael Smith Stephen Smith Jan Sorensen Jon S. Stevens James Strachan Leo Sutic Chris Tilden Neil O'Toole Jeff Turner Kazuya Ujihara Jeff Varszegi Ralph Wagner David Weinrich Dieter Wimberger Serhiy Yevtushenko Jason van Zyl junit junit 3.8.1 test 1.2 1.2 collections 3.2.1 -bin COLLECTIONS 12310465 src/java src/test org.apache.maven.plugins maven-surefire-plugin org/apache/commons/collections/TestAllPackages.java maven-antrun-plugin package run maven-assembly-plugin src/assembly/bin.xml src/assembly/src.xml gnu libcommons-collections3-java.orig/project.properties0000644000175000017500000001025410777673551021411 0ustar godgod# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. maven.repo.remote=http://repo1.maven.org/maven maven.changelog.factory=org.apache.maven.svnlib.SvnChangeLogFactory maven.xdoc.date=left maven.xdoc.version=${pom.currentVersion} maven.xdoc.developmentProcessUrl=http://commons.apache.org/charter.html maven.xdoc.poweredby.image=maven-feather.png maven.xdoc.copy.excludes=images/file.gif,images/folder-closed.gif,images/folder-open.gif,images/icon_alert.gif,images/icon_alertsml.gif,images/icon_arrowfolder1_sml.gif,images/icon_arrowfolder2_sml.gif,images/icon_arrowmembers1_sml.gif,images/icon_arrowmembers2_sml.gif,images/icon_arrowusergroups1_sml.gif,images/icon_arrowusergroups2_sml.gif,images/icon_confirmsml.gif,images/icon_help_lrg.gif,images/icon_infosml.gif,images/icon_members_sml.gif,images/icon_sortleft.gif,images/icon_sortright.gif,images/icon_usergroups_sml.gif,images/icon_waste_lrg.gif,images/icon_waste_sml.gif,images/none.png,images/nw_maj.gif,images/nw_maj_hi.gif,images/nw_med.gif,images/nw_med_hi.gif,images/nw_med_rond.gif,images/nw_min.gif,images/nw_min_036.gif,images/nw_min_hi.gif,images/poweredby_036.gif,images/product_logo.gif,images/se_maj_rond.gif,images/sw_min.gif,images/logos/** maven.xdoc.copy.excludes.classic=images/external-classic.png,images/help_logo.gif,images/icon_arrowfolderclosed1_sml.gif,images/icon_arrowwaste1_sml.gif,images/icon_arrowwaste2_sml.gif,images/icon_doc_lrg.gif,images/icon_doc_sml.gif,images/icon_error_lrg.gif,images/icon_folder_lrg.gif,images/icon_folder_sml.gif,images/icon_help_sml.gif,images/icon_info_lrg.gif,images/icon_members_lrg.gif,images/icon_sortdown.gif,images/icon_sortup.gif,images/icon_success_lrg.gif,images/icon_usergroups_lrg.gif,images/icon_arrowfolderopen2_sml.gif,images/icon_warning_lrg.gif,images/newwindow-classic.png,images/nw_maj_rond.gif,images/strich.gif,images/sw_maj_rond.gif,images/sw_med_rond.gif # Jar Manifest Additional Attributes maven.jar.manifest.attributes.list=Implementation-Vendor-Id,X-Compile-Source-JDK,X-Compile-Target-JDK maven.jar.manifest.attribute.Implementation-Vendor-Id=org.apache maven.jar.manifest.attribute.X-Compile-Source-JDK=${maven.compile.source} maven.jar.manifest.attribute.X-Compile-Target-JDK=${maven.compile.target} maven.javadoc.author=false maven.javadoc.links=http://java.sun.com/j2se/1.4/docs/api/ maven.javadoc.source=1.3 #maven.javadoc.additionalparam=-tag todo:a:"To Do:" maven.javadoc.overview=src/java/org/apache/commons/collections/overview.html #maven.javadoc.public=true #maven.javadoc.package=false #maven.javadoc.private=false maven.checkstyle.properties=checkstyle.xml maven.jdiff.new.tag=CURRENT maven.jdiff.old.tag=COLLECTIONS_3_1 # Generate class files for specific VM version (e.g., 1.1 or 1.2). # Note that the default value depends on the JVM that is running Ant. # In particular, if you use JDK 1.4+ the generated classes will not be usable # for a 1.1 Java VM unless you explicitly set this attribute to the value 1.1 # (which is the default value for JDK 1.1 to 1.3). maven.compile.target = 1.1 # Specifies the source version for the Java compiler. # Corresponds to the source attribute for the ant javac task. # Valid values are 1.3, 1.4, 1.5. maven.compile.source = 1.2 maven.compile.target = 1.2 maven.compile.debug=on maven.compile.deprecation=off maven.compile.optimize=off maven.jarResources.basedir=src/java maven.jar.excludes=**/package.html maven.junit.fork=true clover.excludes=**/Test*.java libcommons-collections3-java.orig/project.xml0000644000175000017500000003243010777673551020015 0ustar godgod 3 commons-collections commons-collections 3.2.1 2001 Collections Commons Collections Types that extend and augment the Java Collections Framework. /images/logo.png http://commons.apache.org/collections/ org.apache.commons.collections The Apache Software Foundation http://commons.apache.org/ http://commons.apache.org/images/logo.png The Apache Software License, Version 2.0 /LICENSE.txt repo commons http://issues.apache.org/jira/ people.apache.org /www/commons.apache.org/collections/ /www/people.apache.org/builds/commons/collections/ scm:svn:http://svn.apache.org/repos/asf/commons/proper/collections/trunk http://svn.apache.org/repos/asf/commons/proper/collections/trunk Commons Dev List dev-subscribe@commons.apache.org dev-unsubscribe@commons.apache.org http://mail-archives.apache.org/mod_mbox/commons-dev/ Commons User List user-subscribe@commons.apache.org user-unsubscribe@commons.apache.org http://mail-archives.apache.org/mod_mbox/commons-user/ 1.0 1.0 COLLECTIONS_1_0 2.0 2.0 COLLECTIONS_2_0 2.1 2.1 COLLECTIONS_2_1 2.1.1 2.1.1 COLLECTIONS_2_1_1 3.0 3.0 COLLECTIONS_3_0 3.1 3.1 COLLECTIONS_3_1 Stephen Colebourne scolebourne Morgan Delagrange morgand Matthew Hawthorne matth Geir Magnusson geirm Craig McClanahan craigmcc Phil Steitz psteitz Arun M. Thomas amamment Rodney Waldhoff rwaldhoff Henri Yandell bayard James Carman jcarman Robert Burrell Donkin rdonkin Rafael U. C. Afonso Max Rydahl Andersen Federico Barbieri Arron Bates Nicola Ken Barozzi Sebastian Bazley Matt Benson Ola Berg Christopher Berry Nathan Beyer Janek Bogucki Chuck Burdick Dave Bryson Julien Buret Jonathan Carlson Ram Chidambaram Steve Clark Eric Crampton Dimiter Dimitrov Peter Donald Steve Downey Rich Dougherty Tom Dunham Stefano Fornari Andrew Freeman Gerhard Froehlich Paul Jack Eric Johnson Kent Johnson Marc Johnson Nissim Karpenstein Shinobu Kawai Mohan Kishore Simon Kitching Thomas Knych Serge Knystautas Peter KoBek Jordan Krey Olaf Krische Guilhem Lavaux Paul Legato David Leppik Berin Loritsch Hendrik Maryns Stefano Mazzocchi Brian McCallister Steven Melzer Leon Messerschmidt Mauricio S. Moura Kasper Nielsen Stanislaw Osinski Alban Peignier Mike Pettypiece Steve Phelps Ilkka Priha Jonas Van Poucke Will Pugh Herve Quiroz Daniel Rall Robert Ribnitz Huw Roberts Henning P. Schmiedehausen Howard Lewis Ship Joe Raysa Thomas Schapitz Jon Schewe Andreas Schlosser Christian Siefkes Michael Smith Stephen Smith Jan Sorensen Jon S. Stevens James Strachan Leo Sutic Chris Tilden Neil O'Toole Jeff Turner Kazuya Ujihara Jeff Varszegi Ralph Wagner David Weinrich Dieter Wimberger Serhiy Yevtushenko Jason van Zyl junit junit 3.8.1 test Required only for testing. maven-plugins maven-cobertura-plugin 1.1.1 http://maven-plugins.sourceforge.net/maven-cobertura-plugin/ plugin test Required only for generating test coverage reports. dev@commons.apache.org src/java src/test org/apache/commons/collections/TestAllPackages.java . META-INF NOTICE.txt maven-checkstyle-plugin maven-pmd-plugin maven-javadoc-plugin maven-jdepend-plugin maven-junit-report-plugin maven-jxr-plugin maven-license-plugin libcommons-collections3-java.orig/PROPOSAL.html0000644000175000017500000000751210777673551017755 0ustar godgod Proposal for Collections Package

              Proposal for Collections Package

              (0) Rationale

              The Java Collections Framework provides a set of abstract data type interfaces and implementations that offer both a wealth of useful functionality, and a solid foundation for extending that functionality.

              Many Jakarta projects have needs or design criteria that extend beyond the core Collections API, such as introducing new abstract data types (e.g., Avalon's BinaryHeap) or changing the behaviour of existing abstract data types (e.g., Struts' FastHashMap).

              In keeping with the spirit of the Collections API and of abstract data types in general, these components can and should be shared assets. A Commons package for abstract data types would encourage the development and reuse of a robust set of collections classes.

              (1) Scope of the Package

              The package will create and maintain a set of collections and related classes designed to be compatible with the Java Collections Framework, and to be distributed under the ASF license.

              (1.5) Interaction With Other Packages

              Collections relies only on standard JDK 1.2 (or later) APIs for production deployment. It utilizes the JUnit unit testing framework for developing and executing unit tests, but this is of interest only to developers of the component. Collections will also be a dependency for several future proposed components for the Jakarta Commons subproject.

              No external configuration files are utilized.

              (2) Initial Source of the Package

              The initial codebase was harvested from existing and proposed Jakarta packages, including the Commons Database Connection Pool, Struts, and Avalon.

              The proposed package name for the new component is org.apache.commons.collections.

              (3) Required Jakarta-Commons Resources

              • CVS Repository - New directory collections in the jakarta-commons CVS repository. All initial committers are already committers on jakarta-commons, so no additional user setups are required.
              • Mailing List - Discussions will take place on the general jakarta-commons@jakarta.apache.org mailing list. To help list subscribers identify messages of interest, it is suggested that the message subject of messages about this component be prefixed with [Collections].
              • Bugzilla - New component "Collections" under the "Commons" product category, with appropriate version identifiers as needed.
              • Jyve FAQ - New category "commons-collections" (when available).

              (4) Initial Committers

              • Peter Donald
              • Craig McClanahan
              • Rodney Waldhoff
              • James Strachan
              libcommons-collections3-java.orig/README.txt0000644000175000017500000000313410777673551017322 0ustar godgodApache Commons Collections =========================== Welcome to the Collections component of the Apache Commons project. This component contains many new collections and collection utilities. Two jar files are produced by this component. The first, commons-collections.jar is the main jar used by applications. The second, commons-collections-testframework.jar is an extension to junit for testing new collection implementations and is not normally used by applications. Building from source -------------------- This component requires the excellent Ant utility. It can be found here : http://ant.apache.org/ For testing the project, you will also need JUnit : http://www.junit.org/ To let the test process find JUnit, you may make a copy of the build.properties.sample file, rename to build.properties, and modify to reflect the location of the junit.jar on your computer. Once you have Ant properly installed, and the build.properties file correctly reflects the location of your junit.jar, you are ready to build and test. The major targets are: ant compile - compile the code ant test - test using junit ant jar - create a jar file ant javadoc - build the javadoc ant dist - create folders as per a distribution ant tf.jar - create the testframework jar file ant tf.javadoc - build the testframework javadoc Maven ----- The component can also be built using Maven. (Ant is the primary build tool.) It can be found here : http://maven.apache.org/ Once installed, the jars may be built with 'maven jar'. libcommons-collections3-java.orig/RELEASE-NOTES.html0000644000175000017500000000266410777673551020467 0ustar godgod RELEASE NOTES: COLLECTIONS 3.2.1

              RELEASE NOTES: COLLECTIONS 3.2.1

              Commons collections is a project to develop and maintain collection classes based on and inspired by the JDK collection framework. This project is JDK1.2 compatible, and does not use JDK1.5 generics.

              This v3.2.1 release is simply a re-packaging of the v3.2 release, with appropriate OSGi meta data added to the jar's manifest file.


              COMPATIBILITY

              This release is fully source and binary compatible with v3.2.